Luminova Framework

PHP Luminova: Array Management Implementation with ArrayUtil Class

Last updated: 2024-08-30 21:07:51

Luminova’s Array Helper class provides useful methods for initializing and managing arrays.

The ArrayUtil 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 namespace: \Luminova\Arrays\ArrayUtil
  • This class implements: Countable, Stringable

Methods

constructor

Constructor to initialize array instance.If no array is provided, an empty array will be initialized.

public __construct(array<string|int,mixed> $array = []): mixed

Parameters:

ParameterTypeDescription
$arrayarray<string|int,mixed>The array to initialize.

Example:

Take note of these initialization variable names, we will make use of then in this documentation for demonstration.

An example of associative array.

<?php 
use Luminova\Arrays\ArrayUtil;

$assoc = new ArrayUtil(['name' => 'Peter', 'age' => 33]);

An example of a nested array.

<?php 
use Luminova\Arrays\ArrayUtil;

$nested = new ArrayUtil(['address' => ['country' => 'Nigeria'], 'about' => ['code' => 'PHP']]);

An example of a list array.

<?php 
use Luminova\Arrays\ArrayUtil;

$list = new ArrayUtil([1, 2, 3]);

fromJson

Create or Update the current array from a json string.

public fromJson(string $json, bool|null $assoc = true, int $depth = 512, int $flags): self

Parameters:

ParameterTypeDescription
$jsonstringThe json string to update from.
$assocbool|nullWeather to convert to an associative array (default: true).
$depthintSet the maximum recursion depth, must be greater than zero (default: 512).
$flagsintThe json decoding flags using bitwise OR (&#124;) operators to combine multiple flags.

Return Value:

self - Return the updated instance with the new array from json string.

Throws:


fromStringList

Create or Update the current array from a string list.

public fromStringList(string $list): self

Parameters:

ParameterTypeDescription
$liststringThe string list to update or create from.

Return Value:

self - Return the updated instance with the new array from string list.

Throws:

Example

Examples of a string list:

<?php 
use Luminova\Arrays\ArrayUtil;
$arr = (new ArrayUtil)->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 isNested(bool $recursive = false): bool

Parameters:

ParameterTypeDescription
$recursiveboolWhether to check deeply nested array values (default: false).

Return Value:

bool - Return true if the array is nested, false otherwise.

Example:

The nested array will pass.

<?php 
var_export($nested->isNested()); // true

The list and associative array will fail.

<?php 
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 isAssoc(): bool

Return Value:

bool - Return true if the array is associative, false otherwise.

Example:

The associative and nested array will pass because they have string key.

<?php 
var_export($assoc->isAssoc()); // true
var_export($nested->isAssoc()); // true

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

<?php 
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 isList(): bool

Return Value:

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.

<?php 
var_export($assoc->isList()); // false
var_export($nested->isList()); // false

The list array will pass because it has integer keys.

<?php 
var_export($list->isList()); // true

isEmpty

Check if array is empty.

public isEmpty(): bool

Return Value:

bool - Return true if the array empty, false otherwise.


get

Get an element from the array based on the provided key.

public get(string|int|null $key = null, mixed $default = null): mixed

Parameters:

ParameterTypeDescription
$keystring|int|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 Value:

mixed - Return the value for the specified key or default value, If key is null return the entire array.

Example:

Get Property key.

<?php 
var_export($assoc->get('name')); // Peter

To return all elements of the array

<?php 
print_r($assoc->get()); // Array

getNested

Retrieves a nested value from the current array using a dot notation for nested keys.

public getNested(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 Value:

mixed - Return the value for the specified notations, or the default value if not found.

Example:

Retrieve the country name from initialized nested array.

<?php 
echo $nested->getNested('address.country'); // Nigeria

add

Add or update an element in the array.

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

Parameters:

ParameterTypeDescription
$keystring|intThe key for the element.
$valuemixedThe value to be added.

Return Value:

self - Return the updated instance with the new element.


add

Add or update an element in the current array using nested dot notation.

public addNested(string $notations, mixed $value): self

Parameters:

ParameterTypeDescription
$keystring|intThe dot notation path to the nested key.
$valuemixedThe value to set at the nested key.

Return Value:

self - Return the updated instance with the new element.

Example

This example will add new element to the nested initialized array.

<?php
$nested->addNested('address.zip.code', '12345');

count

Count the number of elements in the current array.

public count(): int

Return Value:

int - Return the number of elements in the array.


has

Check if the array contains an element with the given key.

public has(string|int $key): bool

Parameters:

ParameterTypeDescription
$keystring|intThe array key to check.

Return Value:

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 diff(ArrayUtil|array ...$arrays): array

Parameters:

ParameterTypeDescription
...$arraysArrayUtil|arrayOne or more arrays or ArrayUtil instances to compare.

Return Value:

array - 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 sort(int $flags = SORT_REGULAR): self

Parameters:

ParameterTypeDescription
$flagsintThe array sort flags (default: SORT_REGULAR).

Return Value:

self - Return the updated instance with the sorted element.


remove

Remove an array key if it exist.

public remove(string|int $key): bool

Parameters:

ParameterTypeDescription
$keystring|intThe array key to remove.

Return Value:

bool - Return true if array key was removed, false otherwise.


clear

Clear all elements from the array.

public clear(): bool

Return Value:

bool - Return true if the entire array was cleared, false otherwise.


keys

Extract all the keys or a subset of the keys in the current array.

public keys(mixed $filter, bool $strict = false): array

Parameters:

ParameterTypeDescription
$filtermixedIf filter value is specified, then only keys containing these values are returned.
$strictboolDetermines if strict comparison (===) should be used during the search (default: false).

Return Value:

array - Return list of array keys in the current array.


values

Extract all the values in the current array.

public values(): array

Return Value:

array - Return list of array values in the current array.


iterator

Extract all the values in the current array.

public iterator(int $flags = 0): \ArrayIterator

Parameters:

ParameterTypeDescription
$flagsintOptional flags to control the behavior of the ArrayObject object (default: 0).

Return Value:

\ArrayIterator - Return a new instance of array iterator containing the current array elements.


column

Extract a column from a multidimensional array.

public column(string|int|null $property, string|int|null $index = null): \Luminova\Arrays\ArrayUtil

Parameters:

ParameterTypeDescription
$propertystring|int|nullThe column to extract.
$indexstring|int|nullThe index to use for extraction.

Return Value:

\Luminova\Arrays\ArrayUtil - Return a new instance of ArrayUtil containing the extracted column.


pluck

Extracts values from an array of associative arrays or objects based on a specified key or property.

public pluck(string $property): \Luminova\Arrays\ArrayUtil

Parameters:

ParameterTypeDescription
$propertystringThe key or property name to pluck values from.

Return Value:

\Luminova\Arrays\ArrayUtil - Return a new instance of ArrayUtil containing the values corresponding to the specified property name.

Example:

<?php
use Luminova\Arrays\ArrayUtil;

$arr = new ArrayUtil([
    ['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.

<?php
class User
{
    public function __construct(public int $id, public string $name){}
}

$arr = new ArrayUtil([
    new User(1, 'Peter'),
    new User(2, 'Hana'),
    new User(3, 'Doe')
]);

$names = $arr->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 search(mixed $search, bool $strict = true, bool $forKey = false): string|int|false

Parameters:

ParameterTypeDescription
$searchmixedThe value or key to search for.
$strictboolWeather to also check the types of the search in the searching array haystack (default: true).
$forKeyboolWhether to search for a key (defaults: false).

Return Value:

string|int|false - Returns the key or index if found, otherwise returns false.


merge

Merge another array with the current array.

public merge(ArrayUtil|array&lt;string|int,mixed&gt; $array): self

Parameters:

ParameterTypeDescription
$arrayArrayUtil|array<string|int,mixed>The array to merge with the current array.

Return Value:

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 mergeRecursive(ArrayUtil|array&lt;string|int,mixed&gt; $array, bool $distinct = false): self

Parameters:

ParameterTypeDescription
$arrayArrayUtil|array<string|int,mixed>The array to merge with the current array.
$distinctboolWeather to ensure unique values in nested arrays (default: false).

Return Value:

self - Return the updated instance with the merged array.

Example:

<?php
$nested->mergeRecursive(['a' => ['y' => 2], 'c' => 3]);

filter

Iterates over each value in the array passing them to the callback function to filter.

public filter(?callable $callback = null, int $mode = 0): \Luminova\Arrays\ArrayUtil

Parameters:

ParameterTypeDescription
$callbackcallable|nullThe filter callback function (default: null).
$modeintThe array filter mode to use (default: 0).

Return Value:

\Luminova\Arrays\ArrayUtil - Return a new instance of ArrayUtil containing the filters.


map

Applies the callback to the elements of the given arrays.

public map(callable $callback, array ...$arguments): \Luminova\Arrays\ArrayUtil

Parameters:

ParameterTypeDescription
$callbackcallableThe filter callback function (default: null).
$argumentsarrayThe array of arguments to map.

Return Value:

\Luminova\Arrays\ArrayUtil - Return a new instance of ArrayUtil containing the elements after applying callback.


reduce

Iteratively reduce the array to a single value using a callback function.

public 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 Value:

mixed - Return the result of array reduce.


reverse

Update the current array with elements in reverse order.

public reverse(bool $preserve_keys = false): self

Parameters:

ParameterTypeDescription
$preserve_keysboolWeather to preserve the original keys of the current array or reset resulting to sequential numeric keys. (default: false).

Return Value:

self - Return the updated instance with the reversed array.


chunk

Return new array instance by splitting the array into chunks.

public chunk(int $size, bool $preserve_keys = false): \Luminova\Arrays\ArrayUtil

Parameters:

ParameterTypeDescription
$sizeintThe split chunk size.
$preserve_keysboolWeather to preserve the array keys or re-index the chunk numerically (default: false).

Return Value:

\Luminova\Arrays\ArrayUtil - Return a new instance of ArrayUtil containing the chunked array.


slice

Return new array instance containing a slice of current array.

public slice(int $offset, ?int $length = null, bool $preserve_keys = false): \Luminova\Arrays\ArrayUtil

Parameters:

ParameterTypeDescription
$offsetintThe array slice offset.
$lengthint|nullThe array slice length (default: null).
$preserve_keysboolWeather to preserve the array keys or to reorder and reset the array numeric keys (default: false).

Return Value:

\Luminova\Arrays\ArrayUtil - Return a new instance of ArrayUtil containing the slice of 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 __toString(): string

Return Value:

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 toString(bool $throw = true): string

Parameters:

ParameterTypeDescription
$throwboolWeather throw json exception if error occurs (default: true).

Return Value:

string - Return json string of the current array, if throw is false return null on error.

Throws:


toStringList

Convert the current array to to comma string list representation.

public toStringList(): string

Return Value:

string - Return string list representation of the current array.


toJson

Convert the current array to json string representation.

public toJson(int $flags, int $depth = 512, bool $throw = true): string|null

Parameters:

ParameterTypeDescription
$flagsintThe json encoding flags using bitwise OR (&#124;) operators to combine multiple flags.
$depthintSet the maximum depth, must be greater than zero (default: 512).
$throwboolWeather throw json exception if error occurs (default: true).

Return Value:

string|null - Return json string of the current array, if throw is false return null on error.

Throws:


toObject

Convert the current array to json object representation.

public toObject(bool|null $assoc = true, int $flags, int $depth = 512, bool $throw = true): object|null

Parameters:

ParameterTypeDescription
$assocbool|nullWeather to convert to an associative array (default: true).
$flagsintThe json encoding flags using bitwise OR (&#124;) operators to combine multiple flags.
$depthintSet the maximum depth, must be greater than zero (default: 512).
$throwboolWeather throw json exception if error occurs (default: true).

Return Value:

object|null - Return json object of the current array, if throw is false return null on error.

Throws: