clouding / range
A simple library for range object.
v1.1.1
2019-01-11 07:55 UTC
Requires
- php: ^7.1.3
Requires (Dev)
- mockery/mockery: ^1.2
- phpstan/phpstan: ^0.10.7
- phpstan/phpstan-mockery: ^0.10.2
- phpunit/phpunit: ^7.5
- squizlabs/php_codesniffer: ^3.4
This package is auto-updated.
Last update: 2024-11-11 20:57:54 UTC
README
A simple library for Range object.
Table of Contents
Installation
composer require clouding/range
Usage
Create
Create a new instance:
use Clouding\Range\Range; $range = new Range(1, 10);
Create a instance from string:
$range = Range::parse('1..10');
Getters
Get start or end:
echo $range->start; // 1 echo $range->end; // 10
Comparison
Determine contains integer or not:
$range = new Range(1, 10); var_dump($range->contains(5)); // bool(true)
Determine two range instances is equals or not:
$range = new Range(1, 10); $rangeFoo = new Range(1, 10); var_dump($range->equals($rangeFoo)); // bool(true)
Determine two range instances is intersect or not:
$range = new Range(1, 10); $rangeBar = new Range(5, 10); var_dump($range->intersect($rangeBar)); // bool(true)
Conversion
Get the instance as a string:
$range = Range::parse('-5..5'); echo $range; // -5..5 echo $range->toString() // -5..5
Get the instance as an array:
$range = new Range(1, 5); var_dump($range->toArray()); // [1, 2, 3, 4, 5] // with gap 2 var_dump($range->toArray(2)); // [1, 3, 5]
Formatting string:
echo $range->format(':start ~ :end'); // 1 ~ 10 echo $range->format('From :start to :end'); // From 1 to 10
Functions
Execute a callback over each integer of range:
$range = new Range(1, 5); $range->each(function ($int) { echo $int, ', '; }); // 1, 2, 3, 4, 5, $range->each(function ($int) { if ($int >= 3) { return false; } echo $int . ', '; }); // 1, 2, // with gap 2 $range->each(function($int) { echo $int . ', '; }, 2); // 1, 3, 5,
Get random integer of the range:
$range = new Range(1, 10); echo $range->random(); // 3 var_dump($range->random(3)); // [3, 2, 9]