Luminova Framework

PHP Luminova: PHP Array Object Helper Class

Last updated: 2026-11-28 20:57:12

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


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:

ParameterTypeDescription
$arrayarray<array-key,mixed>The array to initialize (default []).
$immutableboolWhether 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
): self

Parameters:

ParameterTypeDescription
$jsonstringJSON representing an object or array.
$depthintSet the maximum recursion depth, must be greater than zero (default: 512).
$flagsintThe 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:


fromList

Create an array object from a string list.

public static function fromList(string $list): self

Parameters:

ParameterTypeDescription
$liststringThe string list to parse.

Return:

self - Returns a new array object containing the parsed list.

Throws:

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): bool

Parameters:

ParameterTypeDescription
$recursiveboolWhether to check deeply nested array values (default: false).
$strictboolWhether 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()); // true

The list and associative array will fail.

var_export($assoc->isNested()); // false
var_export($list->isNested()); // false

isAssoc

Check if the current array is associative, which mean it must use string a named keys.

public function isAssoc(): bool

Return:

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()); // true

The list array will fail, because it has an integer key.

var_export($list->isAssoc()); // false

isList

Check if the current array is a list, which means it must be indexed by consecutive integers keys.

public function isList(): bool

Return:

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()); // false

The list array will pass because it has integer keys.

var_export($list->isList()); // true

isEmpty

Check if array is empty.

public function isEmpty(): bool

Return:

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
): mixed

Parameters:

ParameterTypeDescription
$keystring&#124;int&#124;nullThe key of the element to retrieve, or null to get the entire array (default: null).
$defaultmixedThe 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')); // Peter

To return all elements of the array

print_r($assoc->get()); // Array

getArray

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(): array

Return:

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): mixed

Parameters:

ParameterTypeDescription
$notationsstringThe dot notation path to the value.
$defaultmixedThe 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'); // Nigeria

add

Add or update an element in the array.

public function add(string|int $key, mixed $value): self

Parameters:

ParameterTypeDescription
$keystring&#124;intThe key for the element.
$valuemixedThe 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): self

Parameters:

ParameterTypeDescription
$notationsstringThe dot notation path to the nested key.
$valuemixedThe 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(): int

Return:

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): bool

Parameters:

ParameterTypeDescription
$keystring&#124;intThe 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): self

Parameters:

ParameterTypeDescription
$arraysTraversable&#124;ArrayAccess&#124;Stringable&#124;Arr&#124;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
): self

Parameters:

ParameterTypeDescription
$callback?callableOptional comparison callback (default null).
$flagsintThe array sort flags (default: SORT_REGULAR).
$orderstringSorting order: 'ASC' for ascending (default), 'DESC' for descending.
$preserveKeysboolPreserve original keys when sorting values (default: false).
$byKeyboolSort 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): bool

Parameters:

ParameterTypeDescription
$keystring&#124;intThe 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(): bool

Return:

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): self

Parameters:

ParameterTypeDescription
$filtermixedThe value to match when selecting keys.
$strictboolDetermines 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(): self

Return:

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): Traversable

Parameters:

ParameterTypeDescription
$flagsintOptional 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): self

Parameters:

ParameterTypeDescription
$propertystring&#124;int&#124;nullThe column to extract.
$indexstring&#124;int&#124;nullThe 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): self

Parameters:

ParameterTypeDescription
$propertystringThe 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
// )

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|bool

Parameters:

ParameterTypeDescription
$searchmixedThe value or key to search for.
$strictboolWhether to also check the types of the search in the searching array haystack (default: true).
$forKeyboolWhether 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): self

Parameters:

ParameterTypeDescription
$replacementsIteratorAggregate&#124;ArrayAccess&#124;Stringable&#124;Arr&#124;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): self

Parameters:

ParameterTypeDescription
$arraysIteratorAggregate&#124;ArrayAccess&#124;Stringable&#124;Arr&#124;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
): self

Parameters:

ParameterTypeDescription
$distinctboolWhether to ensure unique values in nested arrays (default: false).
$arraysIteratorAggregate&#124;ArrayAccess&#124;Stringable&#124;Arr&#124;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
): self

Parameters:

ParameterTypeDescription
$intervalsintThe positive interval between insertions (default: 4).
$arraysIteratorAggregate&#124;ArrayAccess&#124;Stringable&#124;Arr&#124;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): self

Parameters:

ParameterTypeDescription
$callback?callableThe filter callback function (default: null).
$modeintThe 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): self

Parameters:

ParameterTypeDescription
$callbackcallableThe filter callback function (default: null).
$arraysmixedThe 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): mixed

Parameters:

ParameterTypeDescription
$callbackcallableThe reduce callback function (default: null).
$initialmixedIf 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): self

Parameters:

ParameterTypeDescription
$preserveKeysboolWhether 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): self

Parameters:

ParameterTypeDescription
$sizeintThe split chunk size.
$preserveKeysboolWhether 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): self

Parameters:

ParameterTypeDescription
$offsetintThe array slice offset.
$length?intThe array slice length (default: null).
$preserveKeysboolWhether 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(): string

Return:

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): string

Parameters:

ParameterTypeDescription
$throwboolWhether 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:


toList

Convert the current array to to comma string list representation.

public function toList(): string

Return:

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
): ?string

Parameters:

ParameterTypeDescription
$flagsintThe json encoding flags using bitwise OR (|) operators to combine multiple flags (default JSON_THROW_ON_ERROR).
$depthintSet 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:


toObject

Convert the current array to json object representation.

public function toObject(
    int $flags = JSON_THROW_ON_ERROR,
    int $depth = 512
): ?object

Parameters:

ParameterTypeDescription
$flagsintThe json encoding flags using bitwise OR (|) operators to combine multiple flags (default JSON_THROW_ON_ERROR).
$depthintSet 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:


of

Create a new array instance.

public static function of(array $array, bool $immutable = true): self

Parameters:

ParameterTypeDescription
$arrayarray<array-key,mixed>The initial array data.
$immutableboolWhether 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): self

Parameters:

ParameterTypeDescription
$stateboolWhether 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|string

Parameters:

ParameterTypeDescription
$objectboolIf 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(): mixed

Return:

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(): mixed

Return:

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): self

Parameters:

ParameterTypeDescription
$elementsintThe number of elements in the array (default 0).
$valuesarray<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): self

Parameters:

ParameterTypeDescription
$flagsintSorting 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): self

Parameters:

ParameterTypeDescription
$valuemixedThe 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): self

Parameters:

ParameterTypeDescription
$arrayIteratorAggregate&#124;ArrayAccess&#124;Stringable&#124;Arr&#124;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): self

Parameters:

ParameterTypeDescription
$key?stringKey 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): mixed

Parameters:

ParameterTypeDescription
$key?stringKey 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(): array

Return:

array<array-key,mixed> - Returns the internal array representation.


jsonSerialize

Specify data which should be serialized to JSON.

public function jsonSerialize(): mixed

Return:

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
): ?string

Parameters:

ParameterTypeDescription
$objectboolUse false to return the JSON string (default false).
$flagsintJSON encoding flags combined with bitwise OR (&#124;), (default: JSON_THROW_ON_ERROR &#124; JSON_PRETTY_PRINT).
$depthintMaximum 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): array

Parameters:

ParameterTypeDescription
$arraysmixedOne 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
): void

Parameters:

ParameterTypeDescription
$itemsarray<array-key,mixed>The array to apply prioritize sorting (passed by reference).
$keywordsarray<int,string>&#124;stringA keyword or list of keywords to prioritize.
$indexstring&#124;intThe key name or index in each item to check for matches (default: 0).
$nestedstring&#124;int&#124;nullOptional nested key or index within the target field (default: null).
$limit?intOptional limit on how many comparison checks to perform (default: all).
$slice?intOptional 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): array

Parameters:

ParameterTypeDescription
$sourcemixedThe 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): bool

Parameters:

ParameterTypeDescription
$offsetstring\|intKey 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): mixed

Parameters:

ParameterTypeDescription
$offsetstring\|intKey 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): void

Parameters:

ParameterTypeDescription
$offsetstring\|int\|nullKey to write, or null to append.
$valuemixedValue to store.

offsetUnset

Remove a value by array key.

public function offsetUnset(mixed $offset): void

Parameters:

ParameterTypeDescription
$offsetstring\|intKey in the underlying array.

getIterator

Get the iterator used by foreach.

public function getIterator(): Traversable

Return:

Traversable - Returns the iterator for the wrapped array.