Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Static utility class for working with the PHP array primitive type.
- */
- abstract class Arrays
- {
- /**
- * Unsets and returns the value at index $key in the given array.
- *
- * Example:
- * <br />
- * <pre>
- * use Chadicus\Util\Arrays;
- * $array = ['a', 'b', 'c'];
- * $result = Arrays::getAndUnset($array, 1);
- * var_dump($result);
- * var_dump($array);
- * </pre>
- * <br />
- * Output:
- * <pre>
- * string(1) "b"
- * array(2) {
- * [0] =>
- * string(1) "a"
- * [2] =>
- * string(1) "c"
- * }
- * </pre>
- *
- * @param array &$array The array that contains a value at index $key.
- * @param integer|string $key The key in $array to unset and value to be returned.
- *
- * @return mixed
- */
- final public static function getAndUnset(array &$array, $key)
- {
- if (!array_key_exists($key, $array)) {
- return null;
- }
- $result = $array[$key];
- unset($array[$key]);
- return $result;
- }
- /**
- * Move the element at index $sourceKey to index $destinationKey.
- *
- * Example:
- * <pre>
- * use Chadicus\Util\Arrays;
- * $array = ['foo' => 'bar'];
- * Arrays::rename($array, 'foo', 'goo');
- * var_dump($array);
- * </pre>
- * Output:
- * <pre>
- * array(1) {
- * 'goo' =>
- * string(3) "bar"
- * }
- * </pre>
- *
- * @param array &$array The array that contains a value at index $sourceKey.
- * @param string $sourceKey The index of the source value.
- * @param string $destinationKey The new index name.
- *
- * @return void
- */
- final public static function rename(array &$array, $sourceKey, $destinationKey)
- {
- if (array_key_exists($sourceKey, $array)) {
- $array[$destinationKey] = $array[$sourceKey];
- unset($array[$sourceKey]);
- return;
- }
- }
- /**
- * Attempts to divide the given input array into groups of equal size.
- *
- * @param array $input The array to batch.
- * @param int $batchSize The size of each group.
- *
- * @return array
- */
- final public static function batch(array $input, $batchSize)
- {
- return array_chunk($input, ceil(count($input)/$batchSize), true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement