PHP Luminova: PHP Array Object Helper Class
Luminova’s Array Helper class provides useful methods for initializing and managing arrays.
The Arr class provides a set of methods to facilitate common operations and manipulations on PHP arrays. It includes methods for checking array types, merging arrays, filtering elements, and more.
Class Definition
- Class namespace:
Luminova\Components\Collections\Arr - This class implements:
Luminova\Interface\ArrayableInterface- \ArrayAccess
- \IteratorAggregate
- \Countable
- \Stringable
Methods
constructor
Constructor to initialize array instance.
If no array is provided, an empty array will be initialized.
public function __construct(
array $array = [],
bool $immutable = true
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$array | array<array-key,mixed> | The array to initialize (default []). |
$immutable | bool | Whether this instance should behave immutably (default: true). |
Example:
Take note of these initialization variable names, we will make use of then in this documentation for demonstration.
An example of associative array.
use Luminova\Components\Collections\Arr;
$assoc = new Arr(['name' => 'Peter', 'age' => 33]);An example of a nested array.
use Luminova\Components\Collections\Arr;
$nested = new Arr([
'address' => ['country' => 'Nigeria'],
'about' => ['code' => 'PHP']
]);An example of a list array.
use Luminova\Components\Collections\Arr;
$list = new Arr([1, 2, 3]);fromJson
Create an array object from a JSON string.
public static function fromJson(
string $json,
int $depth = 512,
int $flags = 0
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$json | string | JSON representing an object or array. |
$depth | int | Set the maximum recursion depth, must be greater than zero (default: 512). |
$flags | int | The json decoding flags using bitwise OR (|) operators to combine multiple flags (default 0). |
Return:
self - Returns a new array object containing the decoded data.
Throws:
- Luminova\Exceptions\JsonException - Throws if unable to convert json string to array.
fromList
Create an array object from a string list.
public static function fromList(string $list): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$list | string | The string list to parse. |
Return:
self - Returns a new array object containing the parsed list.
Throws:
- Luminova\Exceptions\RuntimeException - Throws if unable to convert string list to array.
Example
Examples of a string list:
use Luminova\Components\Collections\Arr;
$arr = (new Arr)->fromList(
'name=Peter,age=33,[country=Nigeria;city=EN]'
);print_r($arr->get());
// Output:
// Array
// (
// [name] => Peter
// [age] => 33
// [0] => Array
// (
// [country] => Nigeria
// [city] => EN
// )
// )isNested
Check if the current array is a nested array by containing array as value.If the recursive argument is true, it will also check the values.
public function isNested(bool $recursive = false, bool $strict = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$recursive | bool | Whether to check deeply nested array values (default: false). |
$strict | bool | Whether to require all values to be arrays (default: false). |
Return:
bool - Return true if the array is nested, false otherwise.
Example:
The nested array will pass.
var_export($nested->isNested()); // trueThe list and associative array will fail.
var_export($assoc->isNested()); // false
var_export($list->isNested()); // falseisAssoc
Check if the current array is associative, which mean it must use string a named keys.
public function isAssoc(): boolReturn:
bool - Return true if the array is associative, false otherwise.
Example:
The associative and nested array will pass because they have string key.
var_export($assoc->isAssoc()); // true
var_export($nested->isAssoc()); // trueThe list array will fail, because it has an integer key.
var_export($list->isAssoc()); // falseisList
Check if the current array is a list, which means it must be indexed by consecutive integers keys.
public function isList(): boolReturn:
bool - Return true if the array is a list, false otherwise.
Example:
The associative and nested array will fail because they both have a string key.
var_export($assoc->isList()); // false
var_export($nested->isList()); // falseThe list array will pass because it has integer keys.
var_export($list->isList()); // trueisEmpty
Check if array is empty.
public function isEmpty(): boolReturn:
bool - Return true if the array empty, false otherwise.
get
Get an element from the array based on the provided key.
public function get(
string|int|null $key = null,
mixed $default = null
): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|int|null | The key of the element to retrieve, or null to get the entire array (default: null). |
$default | mixed | The default value if the array key was not found (default: null). |
Return:
mixed - Return the value for the specified key or default value, If key is null return the entire array.
Example:
Get Property key.
var_export($assoc->get('name')); // PeterTo return all elements of the array
print_r($assoc->get()); // ArraygetArray
Retrieve the modified array after processing.
This method returns the internally stored array, which may have been modified by other operations such as merging, filtering, or reordering.
public function getArray(): arrayReturn:
array<array-key,mixed> - Return the processed array.
getAccessor
Retrieves a nested value from the current array using a dot notation for nested keys.
public function getAccessor(string $notations, mixed $default = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$notations | string | The dot notation path to the value. |
$default | mixed | The default value to return if the path is not found. Defaults to null. |
Return:
mixed - Return the value for the specified notations, or the default value if not found.
Example:
Retrieve the country name from initialized nested array.
echo $nested->getAccessor('address.country'); // Nigeriaadd
Add or update an element in the array.
public function add(string|int $key, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|int | The key for the element. |
$value | mixed | The value to be added. |
Return:
self - Return the updated instance with the new element.
accessor
Add or update an element in the current array using nested dot notation.
public function accessor(string $notations, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$notations | string | The dot notation path to the nested key. |
$value | mixed | The value to set at the nested key. |
Return:
self - Return the updated instance with the new element.
Example
This example will add new element to the nested initialized array.
$nested->accessor('address.zipCode', '12345');
echo $nested->getAccessor('address.zipCode'); // 12345
print_r($nested->get('address'));
// Array('zipCode' => '12345')count
Count the number of elements in the current array.
public function count(): intReturn:
int - Return the number of elements in the array.
has
Check if the array contains an element with the given key.
public function has(string|int $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|int | The array key to check. |
Return:
bool - Return true if array key exists, false otherwise.
diff
Compares the current array with one or more arrays and returns the difference.The values from the current array that are not present in any of the passed arrays.
public function diff(Traversable|ArrayAccess|Stringable|Arr|array ...$arrays): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$arrays | Traversable|ArrayAccess|Stringable|Arr|array<array-key,mixed> | One or more arrays or Arr instances to compare. |
Return:
self - Returns an array containing all the entries from the current array that are not present in any of the other arrays.
sort
Sort the current array elements.
public function sort(
?callable $callback = null,
int $flags = SORT_REGULAR,
string $order = 'ASC',
bool $preserveKeys = false,
bool $byKey = false
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | ?callable | Optional comparison callback (default null). |
$flags | int | The array sort flags (default: SORT_REGULAR). |
$order | string | Sorting order: 'ASC' for ascending (default), 'DESC' for descending. |
$preserveKeys | bool | Preserve original keys when sorting values (default: false). |
$byKey | bool | Sort by array keys instead of values (default: false). |
Return:
self - Return the updated instance with the sorted element.
remove
Remove an array key if it exist.
public function remove(string|int $key): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string|int | The array key to remove. |
Return:
bool - Return true if array key was removed, false otherwise.
clear
Clear all elements from the array.
public function clear(): boolReturn:
bool - Return true if the entire array was cleared, false otherwise.
keys
Find the keys whose values match the supplied filter. Use array_keys($arr->getArray()) to retrieve all keys.
public function keys(mixed $filter, bool $strict = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$filter | mixed | The value to match when selecting keys. |
$strict | bool | Determines if strict comparison (===) should be used during the search (default: false). |
Return:
self - Returns a new instance containing array keys from the current array.
values
Extract all the values in the current array.
public function values(): selfReturn:
self - Returns a new instance containing array values from the current array.
iterator
Extract all the values in the current array.
public function iterator(int $flags = 0): TraversableParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Optional flags to control the behavior of the ArrayObject object (default: 0). |
Return:
Traversable - Return an instance of an object implementing Iterator or Traversable.
column
Extract a column from a multidimensional array.
public function column(string|int|null $property, string|int|null $index = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$property | string|int|null | The column to extract. |
$index | string|int|null | The index to use for extraction. |
Return:
self - Returns a new instance containing the extracted column.
pluck
Extracts values from an array of associative arrays or objects based on a specified key or property.
public function pluck(string $property): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$property | string | The key or property name to pluck values from. |
Return:
self - Returns a new instance containing the values corresponding to the specified property name.
Example:
use Luminova\Components\Collections\Arr;
$arr = new Arr([
['name' => 'Peter', 'age' => 33],
['name' => 'Hana', 'age' => 25],
]);
$names = $arr->pluck('name');
print_r($names);
// Output:
// Array
// (
// [0] => Peter
// [1] => Hana
// )Using an object with pluck.
class User
{
public function __construct(public int $id, public string $name){}
}
$users = new Arr([
new User(1, 'Peter'),
new User(2, 'Hana'),
new User(3, 'Doe')
]);
$names = $users->pluck('name');
print_r($names);
// Output:
// Array
// (
// [0] => Peter
// [0] => Hana
// [1] => Doe
// )search
Searches for a value or key in the current array and returns the corresponding key or index.
public function search(mixed $search, bool $strict = true, bool $forKey = false): string|int|boolParameters:
| Parameter | Type | Description |
|---|---|---|
$search | mixed | The value or key to search for. |
$strict | bool | Whether to also check the types of the search in the searching array haystack (default: true). |
$forKey | bool | Whether to search for a key (defaults: false). |
Return:
string|int|bool - Returns the key or index if found, otherwise returns false.
replace
Replace the current array with another array.
public function replace(IteratorAggregate|ArrayAccess|Stringable|Arr|array ...$replacements): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$replacements | IteratorAggregate|ArrayAccess|Stringable|Arr|array<array-key,mixed> | The array to replace with the current array. |
Return:
self - Return the updated instance with the merged array.
merge
Merge another array with the current array.
public function merge(IteratorAggregate|ArrayAccess|Stringable|Arr|array ...$arrays): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$arrays | IteratorAggregate|ArrayAccess|Stringable|Arr|array<array-key,mixed> | The array to merge with the current array. |
Return:
self - Return the updated instance with the merged array.
mergeRecursive
Recursively merges multiple arrays. Values from later arrays will overwrite values from earlier arrays, including merging nested arrays.
public function mergeRecursive(
bool $distinct = false,
IteratorAggregate|ArrayAccess|Stringable|Arr|array ...$arrays
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$distinct | bool | Whether to ensure unique values in nested arrays (default: false). |
$arrays | IteratorAggregate|ArrayAccess|Stringable|Arr|array<array-key,mixed> | The array to merge with the current array. |
Return:
self - Return the updated instance with the merged array.
Example:
$nested->mergeRecursive(false, ['a' => ['y' => 2], 'c' => 3]);mergeIntervals
Merges the given array into the current array at specified intervals.
The method inserts one supplied array as an item at each interval in the current list. If any supplied arrays remain, it inserts them at random positions.
public function mergeIntervals(
int $intervals = 4,
IteratorAggregate|ArrayAccess|Stringable|Arr|array ...$arrays
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$intervals | int | The positive interval between insertions (default: 4). |
$arrays | IteratorAggregate|ArrayAccess|Stringable|Arr|array<array-key,mixed> | Arrays to insert, one per variadic argument. |
Return:
self - Returns the instance with the modified array.
Example:
Merging Posts with Advertisements:
$posts = [
["id" => 1, "title" => "Post 1"],
["id" => 2, "title" => "Post 2"],
["id" => 3, "title" => "Post 3"],
["id" => 4, "title" => "Post 4"]
];
$adverts = [
["id" => 101, "title" => "Ad 1"],
["id" => 102, "title" => "Ad 2"],
["id" => 103, "title" => "Ad 3"],
];
$array = (new Arr($posts))->mergeIntervals($adverts, 2);
print_r($array->getArray());filter
Iterates over each value in the array passing them to the callback function to filter.
public function filter(?callable $callback = null, int $mode = 0): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | ?callable | The filter callback function (default: null). |
$mode | int | The array filter mode to use (default: 0). |
Return:
self - Returns a new instance containing the filters.
map
Applies the callback to the elements of the given arrays.
public function map(callable $callback, mixed ...$arrays): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | callable | The filter callback function (default: null). |
$arrays | mixed | The array of arguments to map. |
Return:
self - Returns a new instance containing the elements after applying callback.
reduce
Iteratively reduce the array to a single value using a callback function.
public function reduce(callable $callback, mixed $initial = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$callback | callable | The reduce callback function (default: null). |
$initial | mixed | If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty. |
Return:
mixed - Return the result of array reduce.
reverse
Update the current array with elements in reverse order.
public function reverse(bool $preserveKeys = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$preserveKeys | bool | Whether to preserve the original keys of the current array or reset resulting to sequential numeric keys. (default: false). |
Return:
self - Return the updated instance with the reversed array.
chunk
Return new array instance by splitting the array into chunks.
public function chunk(int $size, bool $preserveKeys = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$size | int | The split chunk size. |
$preserveKeys | bool | Whether to preserve the array keys or re-index the chunk numerically (default: false). |
Return:
self - Returns a new instance containing the chunked array.
slice
Return new array instance containing a slice of current array.
public function slice(int $offset, ?int $length = null, bool $preserveKeys = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$offset | int | The array slice offset. |
$length | ?int | The array slice length (default: null). |
$preserveKeys | bool | Whether to preserve the array keys or to reorder and reset the array numeric keys (default: false). |
Return:
self - Returns a new instance containing the sliced portion of the array.
Note:
- If length is given and is positive, then the sequence will have that many elements in it.
- If length is given and is negative then the sequence will stop that many elements from the end of the array.
- If it is omitted, then the sequence will have everything from offset up until the end of the array.
__toString
Convert the current array to to json string representation.
public function __toString(): stringReturn:
string - Return json string of the current array or blank string if error occurred.
toString
Convert the current array to to json string representation.
public function toString(bool $throw = true): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$throw | bool | Whether throw json exception if error occurs (default: true). |
Return:
string - Returns the JSON string, or an empty string on encoding failure when $throw is false.
Throws:
- Luminova\Exceptions\JsonException - Throws if unable to convert to json string.
toList
Convert the current array to to comma string list representation.
public function toList(): stringReturn:
string - Return string list representation of the current array.
toJson
Convert the current array to json string representation.
public function toJson(
int $flags = JSON_THROW_ON_ERROR,
int $depth = 512
): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | The json encoding flags using bitwise OR (|) operators to combine multiple flags (default JSON_THROW_ON_ERROR). |
$depth | int | Set the maximum depth, must be greater than zero (default: 512). |
Return:
string|null - Returns the JSON string, or null on a handled encoding failure.
Throws:
- Luminova\Exceptions\JsonException - Throws if unable to convert to json string.
toObject
Convert the current array to json object representation.
public function toObject(
int $flags = JSON_THROW_ON_ERROR,
int $depth = 512
): ?objectParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | The json encoding flags using bitwise OR (|) operators to combine multiple flags (default JSON_THROW_ON_ERROR). |
$depth | int | Set the maximum depth, must be greater than zero (default: 512). |
Return:
object|null - Returns an object decoded from an associative array with string keys, or null on a handled encoding or decoding failure.
Throws:
- Luminova\Exceptions\JsonException - Throws if unable to convert to json string or convert to object.
of
Create a new array instance.
public static function of(array $array, bool $immutable = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$array | array<array-key,mixed> | The initial array data. |
$immutable | bool | Whether the instance should be immutable (default: true). |
Return:
self - Returns a new instance of array object.
immutable
Enable or disable immutable mode for all Arr instances.
public function immutable(bool $state = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$state | bool | Whether to enable (true) or disable (false) immutable mode. Default: true. |
Return:
self - Return instance of array class.
minify
Minify an array into a compact PHP code string.
public function minify(bool $object = false): Stringable|stringParameters:
| Parameter | Type | Description |
|---|---|---|
$object | bool | If true, returns a Stringable instance, otherwise returns a plain string (default: false). |
Return:
Stringable|string - Returns a minified PHP array string. - Plain string value. - Stringable object wrapping the minified string if $object is true
pop
Remove and return the last element of the current array.
public function pop(): mixedReturn:
mixed - Returns the removed element, or null if the array is empty.
shift
Remove and return the first element of the current array.
public function shift(): mixedReturn:
mixed - Returns the removed element, or null if the array is empty.
unshift
Add one or more elements to the beginning of the current array.
public function unshift(int &$elements = 0, array ...$values): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$elements | int | The number of elements in the array (default 0). |
$values | array<array-key,mixed> | One or more values to add to the start of the array. |
Return:
self - Returns the current instance after adding the elements.
unique
Return a new array instance containing only unique values.
public function unique(int $flags = SORT_REGULAR): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$flags | int | Sorting type flags to control comparison behavior. - SORT_REGULAR (default): Normal comparison (no type change) - SORT_NUMERIC: Compare items numerically - SORT_STRING: Compare items as strings - SORT_LOCALE_STRING: Compare as strings, based on the current locale - SORT_NATURAL: Compare items using “natural order” like natsort() |
Return:
self - Returns a new instance containing only unique values.
push
Add a value to the end of the array.
public function push(mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to append to the end of the array. |
Return:
self - Returns the updated instance with the new value appended.
set
Replace the current array entirely with a new one.
public function set(IteratorAggregate|ArrayAccess|Stringable|Arr|array $array): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$array | IteratorAggregate|ArrayAccess|Stringable|Arr|array<array-key,mixed> | The new array or array-like object to set. |
Return:
self - Returns the updated instance containing the new array.
min
Get the item with the lowest value for a given key in a list of rows. Pass a field name to compare rows.
public function min(?string $key = null): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | ?string | Key used for comparison in structured arrays. |
Return:
self - Returns an array object containing the lowest matching row, or an empty array object if no row matches.
max
Get the item with the highest value for a given key in a list of rows. Pass a field name to compare rows.
public function max(?string $key = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | ?string | Key used for comparison in structured arrays. |
Return:
mixed - Returns an array object containing the highest matching row, or an empty array object if no row matches.
toArray
Convert the internal array to a native PHP array.
public function toArray(): arrayReturn:
array<array-key,mixed> - Returns the internal array representation.
jsonSerialize
Specify data which should be serialized to JSON.
public function jsonSerialize(): mixedReturn:
mixed - Returns the data to be serialized into JSON.
json
Encode the array as a JSON string. Use the default $object = false for a string result.
public function json(
bool $object = false,
int $flags = JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT,
int $depth = 512
): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$object | bool | Use false to return the JSON string (default false). |
$flags | int | JSON encoding flags combined with bitwise OR (|), (default: JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT). |
$depth | int | Maximum encoding depth, must be greater than zero (default: 512). |
Return:
string|null - Returns the JSON string, or null on a handled encoding failure.
pack
Pack one or more array or array-like arguments into an array of arrays.
public static function pack(mixed ...$arrays): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$arrays | mixed | One or more arrays or array-like objects. |
Return:
array<int,array<array-key,mixed>> - Returns an array of normalized arrays, always safe for unpacking.
prioritize
Prioritizes array items based on keyword matching.
public static function prioritize(
array &$items,
string|array $keywords,
string|int $index = 0,
string|int|null $nested = null,
?int $limit = null,
?int $slice = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$items | array<array-key,mixed> | The array to apply prioritize sorting (passed by reference). |
$keywords | array<int,string>|string | A keyword or list of keywords to prioritize. |
$index | string|int | The key name or index in each item to check for matches (default: 0). |
$nested | string|int|null | Optional nested key or index within the target field (default: null). |
$limit | ?int | Optional limit on how many comparison checks to perform (default: all). |
$slice | ?int | Optional number of items to slice and sort (default: all). |
from
Convert various supported data types into a plain array.
public static function from(mixed $source): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$source | mixed | The source data to convert into an array. Supports: - ArrayObject, IteratorAggregate, Traversable - Arr or any object implementing toArray() - JSON or serialized strings - Scalar |
Return:
array<array-key,mixed> - Returns an array representation of the input source.
offsetExists
Check an array offset using PHP’s isset() semantics.
public function offsetExists(mixed $offset): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$offset | string\|int | Key in the underlying array. |
Return:
bool - Returns true when the key exists and its value is non-null.
offsetGet
Read a value by array key.
public function offsetGet(mixed $offset): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$offset | string\|int | Key in the underlying array. |
Return:
mixed - Returns the stored value or null for an absent key.
offsetSet
Assign a value by key. An explicit null key appends a new entry.
public function offsetSet(mixed $offset, mixed $value): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$offset | string\|int\|null | Key to write, or null to append. |
$value | mixed | Value to store. |
offsetUnset
Remove a value by array key.
public function offsetUnset(mixed $offset): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$offset | string\|int | Key in the underlying array. |
getIterator
Get the iterator used by foreach.
public function getIterator(): TraversableReturn:
Traversable - Returns the iterator for the wrapped array.