Arrays

Phuture\Coherence\Arrays

class Arrays extends StaticClass

Comprehensive array manipulation utility class with advanced data processing capabilities.

This utility class offers a complete toolkit for array manipulation, including a fluent interface, recursive operations with built-in safety limits, and complex data transformations using dot notation, associative arrays, and sophisticated sorting with custom comparators.

Key features:

  • Fluent Interface: Chainable methods for elegant array manipulation and transformation
  • Recursive Operations: Deep array processing with built-in recursion limit protection
  • Advanced Sorting: Multi-dimensional sorting with custom comparators and sort flags
  • Set Operations: Array difference, intersection, and comparison with key/value modes
  • Data Transformation: Normalization, flattening, association, and dot notation utilities
  • Safe Navigation: Null-safe array access with configurable default values
  • Filtering & Querying: Extensive filtering capabilities including regex-based grep
  • Memory Optimization: Reference-based operations for efficient memory usage

Constants

CROSS_JOIN_LIMIT

const CROSS_JOIN_LIMIT = 1000000

Maximum number of elements allowed in cross join results to prevent memory exhaustion.

RECURSION_LIMIT

const RECURSION_LIMIT = 1000

Maximum recursion depth for nested array operations to prevent infinite recursion.

Methods

getReference()

public static function &getReference(array &$array, string|int|array $key): mixed

Retrieves a reference to an array element by key.

This method returns a reference to an array element, allowing you to modify it directly. If the element doesn't exist, it will be created with a null value. This is useful for dynamically building or modifying array structures.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$config = [
 4    'database' => [
 5        'host' => 'localhost'
 6    ]
 7];
 8
 9// Get reference to existing value
10$hostRef = &Arrays::getReference($config, ['database', 'host']);
11$hostRef = '127.0.0.1';
12// $config['database']['host'] is now '127.0.0.1'
13
14// Get reference to non-existent value (creates it)
15$portRef = &Arrays::getReference($config, ['database', 'port']);
16$portRef = 3306;
17// $config['database']['port'] is now 3306
18
19// Simple key reference
20$debugRef = &Arrays::getReference($config, 'debug');
21$debugRef = true;
22// $config['debug'] is now true
Parameter Type Description
$array array The array to retrieve the reference from (passed by reference)
$key `string int

Returns mixed — Returns a reference to the array element

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — If the traversed item is not an array

See also

  • \Phuture\Coherence\Arrays::get()

accessible()

public static function accessible(mixed $value): bool

Checks if a value can be accessed like an array.

This method determines if a given value supports array-style access using square brackets. Returns true for arrays and objects implementing ArrayAccess or Arrayable.

This is useful when you need to verify that a value can be safely accessed with bracket notation before attempting to read or write values using keys.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3Arrays::accessible(['a' => 1, 'b' => 2]);
 4// Returns: true
 5
 6Arrays::accessible('text string');
 7// Returns: false
 8
 9Arrays::accessible(new stdClass());
10// Returns: false
11
12Arrays::accessible(new ArrayObject());
13// Returns: true
Parameter Type Description
$value mixed The value to check for array accessibility.

Returns bool — Returns true if the value can be accessed as an array, false otherwise

append()

public static function append(array &$array, array $items): void

Appends key-value pairs to an array if the keys don't exist.

This method appends new key-value pairs to the end of an array. If a key already exists, it remains unchanged. The array is modified by reference.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'Desk'];
 4Arrays::append($array, ['price' => 100]);
 5// Result: ['name' => 'Desk', 'price' => 100]
 6
 7$array = ['name' => 'Desk', 'price' => null];
 8Arrays::append($array, ['price' => 100, 'color' => 'brown']);
 9// Result: ['name' => 'Desk', 'price' => null, 'color' => 'brown']
10
11$array = [];
12Arrays::append($array, ['user' => 'demo', 'email' => '[email protected]']);
13// Result: ['user' => 'demo', 'email' => '[email protected]']
Parameter Type Description
$array array The array to add key-value pairs to (passed by reference)
$items array Associative array of key-value pairs to append.

See also

  • \Phuture\Coherence\Arrays::prepend()

associate()

public static function associate(array $array, string|int $key, string|int|null $value = null): array

Transforms an array into an associative array according to a specified key.

This method reorganizes a flat array (typically from a database result) into an associative structure. You can specify which field to use as the key, and optionally which field to use as the value. If no value field is specified, the entire item is used.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    ['id' => 1, 'name' => 'John', 'role' => 'admin'],
 5    ['id' => 2, 'name' => 'Mary', 'role' => 'user'],
 6];
 7
 8// Simple key indexing (returns full items)
 9$result = Arrays::associate($users, 'name');
10// Returns: ['John' => ['id' => 1, 'name' => 'John', 'role' => 'admin'], 'Mary' => [...]]
11
12// Key-value mapping
13$result = Arrays::associate($users, 'name', 'role');
14// Returns: ['John' => 'admin', 'Mary' => 'user']
15
16// Use id as key
17$result = Arrays::associate($users, 'id');
18// Returns: [1 => ['id' => 1, ...], 2 => ['id' => 2, ...]]
Parameter Type Description
$array array The array to transform.
$key `string int`
$value `string int

Returns array — Returns an associative array indexed by the specified key

average()

public static function average(array $array): ?float

Calculates the average (arithmetic mean) of values in an array.

This method adds up all the numbers in an array and divides by the count of elements to find the middle value. Think of it like finding the "typical" value in a set of numbers.

If the array is empty, this method returns null. Non-numeric values are filtered out before the calculation.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$numbers = [1, 2, 3, 4, 5];
 4$avg = Arrays::average($numbers);
 5
 6// Returns: 3.0
 7
 8// With decimal values
 9$prices = [10.5, 20.0, 30.5];
10$avg = Arrays::average($prices);
11
12// Returns: 20.333333333333332
13
14// Empty array returns null
15$avg = Arrays::average([]);
16
17// Returns: null
Parameter Type Description
$array array The array containing numeric values

Returns float|null — The average value, or null if the array is empty

See also

  • \Phuture\Coherence\Arrays::sum()
  • \Phuture\Coherence\Arrays::median()

changeKeyCase()

public static function changeKeyCase(array $array, KeyCase $case = KeyCase::Lower): array

Changes the case of all keys in an array.

This method converts all string keys in an array to either lowercase or uppercase. Numeric keys remain unchanged. This is useful when you need to normalize array keys for case-insensitive comparisons or standardize data from external sources.

Example:

 1use Phuture\Coherence\Arrays;
 2use Phuture\Coherence\Enum\KeyCase;
 3
 4$array = ['Name' => 'John', 'EMAIL' => '[email protected]', 'Age' => 30];
 5
 6// Convert to lowercase (default)
 7$lower = Arrays::changeKeyCase($array);
 8// Returns: ['name' => 'John', 'email' => '[email protected]', 'age' => 30]
 9
10// Convert to uppercase
11$upper = Arrays::changeKeyCase($array, KeyCase::Upper);
12// Returns: ['NAME' => 'John', 'EMAIL' => '[email protected]', 'AGE' => 30]
Parameter Type Description
$array array The array whose keys to change case.
$case \Phuture\Coherence\Enum\KeyCase The case to convert keys to — Lower or Upper (default: KeyCase::Lower)

Returns array — Returns a new array with case-changed keys

See also

  • \Phuture\Coherence\Enum\KeyCase

collapse()

public static function collapse(array $array): array

Collapses one level of a multidimensional array.

This method takes an array containing other arrays and merges them into one single array by flattening only one level of nesting. It's useful when you have multiple arrays that you want to combine into a single list while preserving any deeper nested array structures.

Non-array elements are silently skipped, allowing mixed arrays to be collapsed without causing a type error.

Unlike flatten() which recursively flattens all nested levels, collapse() only merges one level of nesting, preserving any deeper nested structures.

Later values overwrite earlier ones for duplicate keys.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$arrays = [[1, 2], [3, 4], [5, 6]];
 4$result = Arrays::collapse($arrays);
 5// Returns: [1, 2, 3, 4, 5, 6]
 6
 7// With associative arrays
 8$arrays = [['a' => 1], ['b' => 2], ['c' => 3]];
 9$result = Arrays::collapse($arrays);
10// Returns: ['a' => 1, 'b' => 2, 'c' => 3]
11
12// With mixed elements (non-array values are skipped)
13$arrays = [1, [2, 3], 'string', [4]];
14$result = Arrays::collapse($arrays);
15// Returns: [2, 3, 4]
Parameter Type Description
$array array An array containing other arrays to merge. Non-array elements are silently skipped.

Returns array — Returns a single flattened array with all values from the nested arrays

See also

  • \Phuture\Coherence\Arrays::flatten()

column()

public static function column(array $array, int|string|array|null $column, int|string|array|null $index = null): array

Extracts values from a single column in a multidimensional array.

This method pulls out values from a specific field across all rows in an array, similar to selecting a column from a spreadsheet. Useful when working with database results or arrays of objects.

You can extract values from nested paths using an array of keys. For example, to get email addresses from a nested user profile structure.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    ['id' => 1, 'name' => 'John'],
 5    ['id' => 2, 'name' => 'Jane'],
 6    ['id' => 3, 'name' => 'Bob']
 7];
 8
 9$names = Arrays::column($users, 'name');
10// Returns: ['John', 'Jane', 'Bob']
11
12// Index by another column
13$indexed = Arrays::column($users, 'name', 'id');
14// Returns: [1 => 'John', 2 => 'Jane', 3 => 'Bob']
15
16// Extract from nested path using array notation
17$users = [
18    ['id' => 1, 'profile' => ['email' => '[email protected]']],
19    ['id' => 2, 'profile' => ['email' => '[email protected]']]
20];
21$emails = Arrays::column($users, ['profile', 'email']);
22// Returns: ['[email protected]', '[email protected]']
23
24// Nested path with index
25$indexed = Arrays::column($users, ['profile', 'email'], 'id');
26// Returns: [1 => '[email protected]', 2 => '[email protected]']
Parameter Type Description
$array array The multidimensional array to extract from.
$column `int string
$index `int string

Returns array — Returns an array of values from the specified column

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — If the column path is not a valid list of strings
  • \Phuture\Coherence\Exception\InvalidDataTypeException — If the array contains invalid data types

combine()

public static function combine(array $keys, array $values): array

Creates an array by pairing keys with values from two separate arrays.

This method takes one array of keys and another array of values, and combines them into a single associative array where the first array provides the keys and the second provides the values. Both arrays must have the same number of elements.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$keys = ['name', 'email', 'age'];
 4$values = ['John', '[email protected]', 30];
 5
 6$result = Arrays::combine($keys, $values);
 7// Returns: ['name' => 'John', 'email' => '[email protected]', 'age' => 30]
 8
 9// Creating a lookup table
10$ids = [1, 2, 3];
11$names = ['Alice', 'Bob', 'Charlie'];
12$lookup = Arrays::combine($ids, $names);
13// Returns: [1 => 'Alice', 2 => 'Bob', 3 => 'Charlie']
Parameter Type Description
$keys array Array of keys to use
$values array Array of values to use

Returns array — Returns an associative array combining the keys and values

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When arrays have different lengths
  • \Phuture\Coherence\Exception\InvalidDataTypeException — When keys contain non-string or non-integer values

contains()

public static function contains(array $array, mixed $value): bool

Checks if a value exists in an array.

This method searches through an array to see if a specific value exists anywhere in it. By default, it uses strict comparison (===) which checks both value and type. You can disable strict mode to use loose comparison (==) which only checks the value.

Example:

1use Phuture\Coherence\Arrays;
2
3$colors = ['red', 'blue', 'green'];
4$hasBlue = Arrays::contains($colors, 'blue');
5// Returns: true
Parameter Type Description
$array array The array to search in.
$value mixed The value to search for.

Returns bool — Returns true if the value exists in the array, false otherwise

See also

  • \Phuture\Coherence\Arrays::exists()
  • \Phuture\Coherence\Arrays::search()

count()

public static function count(array $array): array

Counts how many times each unique value appears in an array.

This method goes through an array and creates a report showing how many times each unique value occurs. The result is an associative array where keys are the values from the original array, and values are the counts.

Example:

1use Phuture\Coherence\Arrays;
2
3$votes = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
4$tally = Arrays::count($votes);
5// Returns: ['apple' => 3, 'banana' => 2, 'orange' => 1]
6
7$numbers = [1, 2, 2, 3, 3, 3];
8$frequency = Arrays::count($numbers);
9// Returns: [1 => 1, 2 => 2, 3 => 3]
Parameter Type Description
$array array The array whose values to count.

Returns array — Returns an associative array with values as keys and occurrence counts as values

See also

  • \Phuture\Coherence\Arrays::length()

crossJoin()

public static function crossJoin(array ...$arrays): array

Creates a Cartesian product of multiple arrays.

This method generates all possible combinations by taking one element from each provided array. For example, if you provide arrays [1, 2] and ['a', 'b'], it will generate all combinations: [1, 'a'], [1, 'b'], [2, 'a'], [2, 'b'].

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic cross join with equal length arrays
 4$result = Arrays::crossJoin([1, 2], ['a', 'b']);
 5// Returns: [
 6//     [1, 'a'],
 7//     [1, 'b'],
 8//     [2, 'a'],
 9//     [2, 'b']
10// ]
11
12// Cross join with three arrays
13$sizes = ['S', 'M'];
14$colors = ['red', 'blue'];
15$types = ['shirt', 'pants'];
16$result = Arrays::crossJoin($sizes, $colors, $types);
17// Returns 8 combinations: ['S', 'red', 'shirt'], ['S', 'red', 'pants'], etc.
Parameter Type Description
...$arrays array Two or more arrays to cross join

Returns array — Returns a multidimensional array containing all possible combinations

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When fewer than 2 arrays provided or any is empty

denote()

public static function denote(array $array, bool $strict = false): array

Expands a flattened array with dot notation keys back into a multidimensional array.

This method takes a flat array where keys use dot notation to represent nested paths and converts it back into a multidimensional array structure. For example, a key like 'user.address.city' becomes ['user']['address']['city'].

This is the reverse operation of the flatten method and is useful when you need to reconstruct complex nested structures from simple key-value pairs.

When $strict is false (default), conflicting keys will result in later values overwriting earlier ones. Keys are processed in natural sort order for deterministic output regardless of input order. When $strict is true, a LogicException will be thrown if conflicts are detected.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$flat = [
 4    'name' => 'John',
 5    'address.city' => 'NYC',
 6    'address.zip' => '10001'
 7];
 8$nested = Arrays::denote($flat);
 9
10// Returns: ['name' => 'John', 'address' => ['city' => 'NYC', 'zip' => '10001']]
Parameter Type Description
$array array The flattened array with dot notation keys.
$strict bool If true, throws exception on data conflicts; if false, later values overwrite earlier ones

Returns array — Returns a multidimensional array with nested structure

Throws

  • \Phuture\Coherence\Exception\LogicException — When $strict is true and a data conflict is detected

See also

  • \Phuture\Coherence\Arrays::notation()

difference()

public static function difference(array $array, ...$arrays): array

Returns elements from the first array that are not present in other arrays.

This method compares values across multiple arrays and returns only those values from the first array that don't appear in any of the other arrays. Keys are preserved.

You can optionally provide a custom comparison function as the last parameter.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic usage
 4$array1 = ['a', 'b', 'c', 'd'];
 5$array2 = ['b', 'd'];
 6$array3 = ['e', 'f'];
 7$result = Arrays::difference($array1, $array2, $array3);
 8// Returns: [0 => 'a', 2 => 'c']
 9
10// With custom comparison function (case-insensitive)
11$array1 = ['Apple', 'Banana', 'Cherry'];
12$array2 = ['banana', 'APPLE'];
13$result = Arrays::difference(
14    $array1,
15    $array2,
16    fn($a, $b) => strcasecmp($a, $b)
17);
18// Returns: [2 => 'Cherry']
19
20// Comparing objects by property
21$products1 = [
22    (object)['id' => 1, 'name' => 'Laptop'],
23    (object)['id' => 2, 'name' => 'Mouse'],
24    (object)['id' => 3, 'name' => 'Keyboard']
25];
26$products2 = [(object)['id' => 2, 'name' => 'Mouse']];
27$result = Arrays::difference(
28    $products1,
29    $products2,
30    fn($a, $b) => $a->id <=> $b->id
31);
32// Returns: [0 => Laptop object, 2 => Keyboard object]
Parameter Type Description
$array array The array to compare from.
...$arrays array Arrays to compare against
$callback `callable null`

Returns array — Returns values from the first array not found in other arrays

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When a comparison array is not provided

See also

  • \Phuture\Coherence\Arrays::differenceAssoc()
  • \Phuture\Coherence\Arrays::differenceKeys()

differenceAssoc()

public static function differenceAssoc(array $array, ...$arrays): array

Returns elements from the first array that are not present in other arrays, comparing both keys and values with optional custom comparison.

This method computes the difference of arrays with additional index check, meaning both the keys and values must match for an element to be considered present in other arrays. You can optionally provide custom comparison functions and specify what to compare (keys, values, or both) using the ArrayComparator enum.

The method supports flexible parameter order where callbacks and the comparator can be provided at the end of the argument list.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2use Phuture\Coherence\Enum\ArrayComparator;
 3
 4// Basic usage
 5$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
 6$array2 = ['a' => 1, 'd' => 4];
 7$result = Arrays::differenceAssoc($array1, $array2);
 8// Returns: ['b' => 2, 'c' => 3]
 9
10// With custom value comparison and comparator
11$array1 = ['name' => 'John', 'AGE' => 30];
12$array2 = ['name' => 'JOHN'];
13$result = Arrays::differenceAssoc(
14    $array1,
15    $array2,
16    ArrayComparator::Value, // compare values using callback
17    fn($a, $b) => strcasecmp($a, $b) // callback for case-insensitive comparison
18);
19// Returns: ['AGE' => 30]
20
21// With custom key comparison
22$array1 = ['Apple' => 100, 'Banana' => 200];
23$array2 = ['apple' => 100];
24$result = Arrays::differenceAssoc(
25    $array1,
26    $array2,
27    ArrayComparator::Key, // compare keys using callback
28    fn($a, $b) => strcasecmp($a, $b) // callback for case-insensitive key comparison
29);
30// Returns: ['Banana' => 200]
31
32// With custom comparison for both keys and values
33$array1 = ['Name' => 'John', 'Age' => 30];
34$array2 = ['name' => 'JOHN', 'age' => 25];
35$result = Arrays::differenceAssoc(
36    $array1,
37    $array2,
38    ArrayComparator::Both, // compare both keys and values using callbacks
39    fn($a, $b) => strcasecmp($a, $b), // callback for value comparison
40    fn($a, $b) => strcasecmp($a, $b)  // callback for key comparison
41);
42// Returns: ['Age' => 30]
Parameter Type Description
$array array The array to compare from.
...$arrays array Arrays to compare against
$comparator ArrayComparator The comparator to use with the provided callback(s) (required with callbacks)
$firstCallback `callable null`
$secondCallback `callable null`

Returns array — Returns key-value pairs from the first array not found in other arrays

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When no comparison arrays are provided, when callbacks are provided without an ArrayComparator OR when more than two callbacks are provided
  • \Phuture\Coherence\Exception\LogicException — When no ArrayComparator enum is provided when needed OR when ArrayComparator::Both is not used with exactly two callbacks

See also

  • \Phuture\Coherence\Arrays::difference()
  • \Phuture\Coherence\Arrays::differenceKeys()
  • \Phuture\Coherence\Enum\ArrayComparator

differenceKeys()

public static function differenceKeys(array $array, ...$arrays): array

Returns keys from the first array that are not present in other arrays.

This method compares only the keys (not values) across multiple arrays and returns key-value pairs from the first array whose keys don't appear in any of the other arrays.

You can optionally provide a custom comparison function as the last parameter.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic usage
 4$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
 5$array2 = ['a' => 99, 'd' => 4];
 6
 7$result = Arrays::differenceKeys($array1, $array2);
 8// Returns: ['b' => 2, 'c' => 3]
 9// (keys 'b' and 'c' don't exist in array2, values don't matter)
10
11// With callback for type-insensitive key comparison
12$array1 = [1 => 'one', 2 => 'two', 3 => 'three'];
13$array2 = ['1' => 'ONE', '2' => 'TWO'];
14
15$result = Arrays::differenceKeys(
16    $array1,
17    $array2,
18    fn($a, $b) => (string)$a <=> (string)$b
19);
20// Returns: [3 => 'three']
21// (numeric keys 1 and 2 match string keys '1' and '2' when compared as strings)
Parameter Type Description
$array array The array to compare from.
...$arrays array Arrays to compare against
$callback `callable null`

Returns array — Returns key-value pairs whose keys are not found in other arrays

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When no comparison array is provided

See also

  • \Phuture\Coherence\Arrays::difference()
  • \Phuture\Coherence\Arrays::differenceAssoc()

every()

public static function every(array $array, callable $callback): bool

Checks if all array elements satisfy a callback function.

This method tests every element in an array against a condition you provide. It only returns true if ALL elements pass the test. Think of it like checking if everyone in a group has completed their homework.

Example:

1use Phuture\Coherence\Arrays;
2
3$numbers = [2, 4, 6, 8];
4$allEven = Arrays::every($numbers, fn($n) => $n % 2 === 0);
5// Returns: true (all numbers are even)
6
7$ages = [18, 21, 16, 25];
8$allAdults = Arrays::every($ages, fn($age) => $age >= 18);
9// Returns: false (16 < 18)
Parameter Type Description
$array array The array whose elements to test.
$callback callable A function that receives each element and returns true if it passes the test The callback has the signature function (mixed $value, mixed $key): bool

Returns bool — Returns true if ALL elements pass the callback test, false otherwise

See also

  • \Phuture\Coherence\Arrays::some()

exists()

public static function exists(array $array, string|int $key): bool

Checks if a key exists in an array.

This method determines whether a specific key exists in an array, regardless of what value is associated with that key. This is useful when you need to check for the presence of a key even if its value is null or empty.

Example:

1use Phuture\Coherence\Arrays;
2
3$user = ['name' => 'John', 'age' => 25, 'email' => null];
4$hasEmail = Arrays::exists($user, 'email');
5// Returns: true (key exists even though value is null)
6
7$hasPhone = Arrays::exists($user, 'phone');
8// Returns: false (key doesn't exist)
Parameter Type Description
$array array The array to search in
$key `string int`

Returns bool — Returns true if the key exists in the array, false otherwise

See also

  • \Phuture\Coherence\Arrays::contains()

fill()

public static function fill(int $startIndex, int $count, mixed $value): array

Creates an array filled with a specific value.

This method generates a new array with a specified number of elements, all set to the same value. The array starts at a given index position, which can be positive or negative. Useful for initializing arrays with default values.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Create array starting at index 0
 4$array = Arrays::fill(0, 3, 'hello');
 5// Returns: [0 => 'hello', 1 => 'hello', 2 => 'hello']
 6
 7// Start at a different index
 8$array = Arrays::fill(5, 3, 'x');
 9// Returns: [5 => 'x', 6 => 'x', 7 => 'x']
10
11// Use negative index
12$array = Arrays::fill(-2, 2, 0);
13// Returns: [-2 => 0, -1 => 0]
Parameter Type Description
$startIndex int The first index of the returned array
$count int Number of elements to insert (must be greater than zero)
$value mixed The value to fill the array with

Returns array — Returns a new array filled with the specified value

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When count is less than or equal to zero

See also

  • \Phuture\Coherence\Arrays::fillKeys()

fillKeys()

public static function fillKeys(array $keys, mixed $value): array

Creates an array using specified keys, all with the same value.

This method generates a new array where you provide the exact keys to use, and all those keys are set to the same value. This is useful when you need to initialize an associative array with specific keys.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Create array with string keys
 4$array = Arrays::fillKeys(['name', 'email', 'phone'], null);
 5// Returns: ['name' => null, 'email' => null, 'phone' => null]
 6
 7// Initialize with default values
 8$permissions = Arrays::fillKeys(['read', 'write', 'delete'], false);
 9// Returns: ['read' => false, 'write' => false, 'delete' => false]
10
11// Use numeric keys
12$array = Arrays::fillKeys([10, 20, 30], 'value');
13// Returns: [10 => 'value', 20 => 'value', 30 => 'value']
Parameter Type Description
$keys array Array of keys to use for the new array
$value mixed The value to assign to all keys

Returns array — Returns a new array with specified keys and the same value for all

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When keys array is empty

See also

  • \Phuture\Coherence\Arrays::fill()

filter()

public static function filter(array $array, ?callable $callback = null): array

Filters elements of an array using a callback function.

This method creates a new array containing only the elements that pass a test you provide. The callback function receives each element and should return true to keep it or false to remove it.

If no callback is provided, it removes all elements that evaluate to false (like null, 0, false, empty string).

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$numbers = [1, 2, 3, 4, 5, 6];
 4
 5// Keep only even numbers
 6$even = Arrays::filter($numbers, fn($n, $k) => $n % 2 === 0);
 7// Returns: [1 => 2, 3 => 4, 5 => 6]
 8
 9// Remove falsy values (no callback)
10$mixed = [0, 1, false, 2, '', 3, null];
11$filtered = Arrays::filter($mixed);
12// Returns: [1 => 1, 3 => 2, 5 => 3]
Parameter Type Description
$array array The array to filter.
$callback `callable null`

Returns array — Returns a new array containing only the filtered elements

See also

  • \Phuture\Coherence\Arrays::grep()
  • \Phuture\Coherence\Arrays::find()

find()

public static function find(array $array, callable $callback): mixed

Returns the first element that passes a test function.

This method searches through an array and returns the first element that makes your test function return true. If no element passes the test, it returns null. This is useful when you need to find a specific item in an array based on a condition.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    ['id' => 1, 'name' => 'John', 'active' => false],
 5    ['id' => 2, 'name' => 'Jane', 'active' => true],
 6    ['id' => 3, 'name' => 'Bob', 'active' => true]
 7];
 8
 9// Find first active user
10$activeUser = Arrays::find($users, fn($user) => $user['active']);
11// Returns: ['id' => 2, 'name' => 'Jane', 'active' => true]
12
13// Find user by name
14$john = Arrays::find($users, fn($user) => $user['name'] === 'John');
15// Returns: ['id' => 1, 'name' => 'John', 'active' => false]
16
17// No match found
18$admin = Arrays::find($users, fn($user) => $user['role'] === 'admin');
19// Returns: null
Parameter Type Description
$array array The array to search through.
$callback callable Function that tests each element, returns true to select it The callback has the signature function (mixed $value, mixed $key): bool

Returns mixed — Returns the first matching element, or null if none found

See also

  • \Phuture\Coherence\Arrays::findKey()

findKey()

public static function findKey(array $array, callable $callback): mixed

Returns the key of the first element that passes a test function.

This method searches through an array and returns the key (not the value) of the first element that makes your test function return true. If no element passes the test, it returns null. Useful when you need to know the position or key of an item.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    'user1' => ['name' => 'John', 'active' => false],
 5    'user2' => ['name' => 'Jane', 'active' => true],
 6    'user3' => ['name' => 'Bob', 'active' => true]
 7];
 8
 9// Find key of first active user
10$key = Arrays::findKey($users, fn($user) => $user['active']);
11// Returns: 'user2'
12
13// With numeric keys
14$numbers = [10, 20, 30, 40];
15$key = Arrays::findKey($numbers, fn($n) => $n > 25);
16// Returns: 2 (the index of 30)
17
18// No match found
19$key = Arrays::findKey($users, fn($user) => $user['role'] === 'admin');
20// Returns: null
Parameter Type Description
$array array The array to search through.
$callback callable Function that tests each element, returns true to select it The callback has the signature function (mixed $value, mixed $key): bool

Returns mixed — Returns the key of the first matching element, or null if none found

See also

  • \Phuture\Coherence\Arrays::find()

first()

public static function first(array $array): mixed

Returns the first value of an array.

This method retrieves the first value from an array without modifying it. The method throws an exception for empty arrays. This is useful for quickly accessing the first element without worrying about array keys or positions.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 4$first = Arrays::first($array);
 5// Returns: 'John'
 6
 7// With numeric array
 8$numbers = [10, 20, 30];
 9$first = Arrays::first($numbers);
10// Returns: 10
11
12// Empty array - throws exception
13$empty = [];
14$first = Arrays::first($empty);
15// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to get the first value from.

Returns mixed — Returns the first value

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When the array is empty

See also

  • \Phuture\Coherence\Arrays::last()

firstKey()

public static function firstKey(array $array): string|int

Returns the first key of an array.

This method retrieves the first key from an array without modifying it. The method throws an exception for empty arrays. The key can be a string or integer.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 4$firstKey = Arrays::firstKey($array);
 5// Returns: 'name'
 6
 7// With numeric keys
 8$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];
 9$firstKey = Arrays::firstKey($numbers);
10// Returns: 10
11
12// Empty array - throws exception
13$empty = [];
14$firstKey = Arrays::firstKey($empty);
15// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to get the first key from.

Returns string|int — Returns the first key

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When the array is empty

See also

  • \Phuture\Coherence\Arrays::lastKey()

flatten()

public static function flatten(array $array, int $depth = 0): array

Flattens a multidimensional array into a single level.

This method recursively flattens all nested arrays into a single-dimensional array. Unlike collapse() which only merges one level of arrays, flatten() recursively traverses through ALL levels of nesting and collects only the scalar values.

Keys from associative arrays are not preserved in the flattened result.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = [1, [2, 3], [4, [5, 6]], 7];
 4$result = Arrays::flatten($array);
 5// Returns: [1, 2, 3, 4, 5, 6, 7]
 6
 7// With associative arrays
 8$array = ['a' => 1, 'b' => ['c' => 2, 'd' => ['e' => 3]]];
 9$result = Arrays::flatten($array);
10// Returns: [1, 2, 3]
Parameter Type Description
$array array A potentially multidimensional array to flatten
$depth int Internal recursion depth tracker (default: 0)

Returns array — Returns a single-dimensional array containing all scalar values from the nested structure

Throws

  • \Phuture\Coherence\Exception\LogicException — When recursion depth exceeds the limit

See also

  • \Phuture\Coherence\Arrays::collapse()

flip()

public static function flip(array $array): array

Exchanges all keys with their associated values in an array.

This method swaps keys and values in an array, so that values become keys and keys become values. If multiple values are the same, only the last key will be preserved in the result.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
 4$flipped = Arrays::flip($array);
 5// Returns: ['apple' => 'a', 'banana' => 'b', 'cherry' => 'c']
 6
 7// Numeric keys become string values
 8$numbers = [1 => 'one', 2 => 'two', 3 => 'three'];
 9$flipped = Arrays::flip($numbers);
10// Returns: ['one' => 1, 'two' => 2, 'three' => 3]
11
12// Duplicate values - last key wins
13$duplicates = ['a' => 'same', 'b' => 'same', 'c' => 'different'];
14$flipped = Arrays::flip($duplicates);
15// Returns: ['same' => 'b', 'different' => 'c']
Parameter Type Description
$array array The array to flip.

Returns array — Returns a new array with flipped keys and values

Throws

  • \Phuture\Coherence\Exception\InvalidDataTypeException — If one of the values is not a string nor integer

See also

  • \Phuture\Coherence\Arrays::reverse()

fromCsv()

public static function fromCsv(string $string, string $separator = ', ', string $enclosure = '"', string $escape = '\\'): array

Parses a CSV-formatted string into an array.

Wraps PHP's native str_getcsv() to parse a single line of CSV text into an indexed array of fields. Supports configurable field separator, field enclosure, and escape characters.

Example:

1use Phuture\Coherence\Arrays;
2
3Arrays::fromCsv('a,b,c'); // ['a', 'b', 'c']
4Arrays::fromCsv('"a","b","c"'); // ['a', 'b', 'c']
5Arrays::fromCsv('a|b|c', '|'); // ['a', 'b', 'c']
6Arrays::fromCsv('a;b;c', ';'); // ['a', 'b', 'c']
Parameter Type Description
$string string The CSV-formatted string to parse
$separator string The field separator character (default: ',')
$enclosure string The field enclosure character (default: '"')
$escape string The escape character (default: '\')

Returns array — The parsed array of CSV fields

See also

  • \Phuture\Coherence\Arrays::fromString()

fromString()

public static function fromString(string $string, string $separator = ' ', int $limit = PHP_INT_MAX): array

Converts a string into an array by splitting it with a separator.

This method takes a string and splits it into an array using the specified separator. It provides a convenient wrapper around PHP's explode() function with consistent parameter ordering and sensible defaults.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic usage with space separator
 4$words = Arrays::fromString('Hello world from Arrays');
 5// Returns: ['Hello', 'world', 'from', 'Arrays']
 6
 7// Using custom separator
 8$fruits = Arrays::fromString('apple,banana,cherry', ',');
 9// Returns: ['apple', 'banana', 'cherry']
10
11// With limit
12$parts = Arrays::fromString('one-two-three-four', '-', 3);
13// Returns: ['one', 'two', 'three-four']
Parameter Type Description
$string string The string to split into an array.
$separator string The character or string to split on (default: space).
$limit int The maximum number of array elements to return (default: PHP's default).

Returns array — An array of string parts.

See also

  • \Phuture\Coherence\Arrays::toString()

get()

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

Retrieves a value from an array by key.

This method provides a safe way to access array values without worrying about undefined key errors. For nested arrays, you can pass an array of keys to navigate through the structure. When a key doesn't exist and no default value was provided, an exception is thrown.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$data = [
 4    'user' => [
 5        'profile' => [
 6            'email' => '[email protected]'
 7        ]
 8    ],
 9    'status' => 'active'
10];
11
12// Access simple key
13$status = Arrays::get($data, 'status');
14// Returns: 'active'
15
16// Access nested value using array path
17$email = Arrays::get($data, ['user', 'profile', 'email']);
18// Returns: '[email protected]'
19
20// Provide default value for missing key
21$role = Arrays::get($data, 'role', 'guest');
22// Returns: 'guest'
23
24// Missing key without default throws exception
25$role = Arrays::get($data, 'role');
26// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to retrieve the value from.
$key `string int
$default mixed Optional default value to return if the key is not found

Returns mixed — Returns the value at the specified key, or the default value if provided and the key doesn't exist

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When the key doesn't exist and no default value is provided

See also

  • \Phuture\Coherence\Arrays::getReference()

grep()

public static function grep(array $array, string $pattern, bool $invert = false): array

Filters array elements by regular expression pattern.

This method returns only those array elements whose values match the specified regular expression pattern. When the invert parameter is true, it returns elements that do NOT match the pattern instead.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$data = ['apple', 'banana', '123', '456', 'cherry'];
 4
 5// Get only numeric strings
 6$numbers = Arrays::grep($data, '~^\d+$~');
 7// Returns: ['123', '456']
 8
 9// Get only non-numeric strings (inverted)
10$words = Arrays::grep($data, '~^\d+$~', true);
11// Returns: ['apple', 'banana', 'cherry']
12
13// Match strings starting with 'a'
14$startsWithA = Arrays::grep($data, '~^a~i');
15// Returns: ['apple']
Parameter Type Description
$array array The array to filter.
$pattern string Regular expression pattern to match against
$invert bool When true, returns elements that do NOT match the pattern (default: false)

Returns array — Returns filtered array with matching elements

Throws

  • \Phuture\Coherence\Exception\LogicException — When the regular expression pattern is invalid

groupBy()

public static function groupBy(array $array, callable|string $groupBy): array

Groups array elements by a specified key or callback function.

This method organizes items in an array into groups based on a common value. You can either specify a key name (for arrays of arrays/objects) or provide a custom function that determines how items should be grouped.

Think of it like sorting a deck of cards into piles by suit - all hearts go in one pile, all spades in another, and so on. Each pile keeps all the original cards together.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Group by key name
 4$users = [
 5    ['name' => 'John', 'department' => 'Sales'],
 6    ['name' => 'Jane', 'department' => 'IT'],
 7    ['name' => 'Bob', 'department' => 'Sales']
 8];
 9$grouped = Arrays::groupBy($users, 'department');
10// Returns: [
11//     'Sales' => [
12//         ['name' => 'John', 'department' => 'Sales'],
13//         ['name' => 'Bob', 'department' => 'Sales']
14//     ],
15//     'IT' => [
16//         ['name' => 'Jane', 'department' => 'IT']
17//     ]
18// ]
19
20// Group by callback function
21$numbers = [1, 2, 3, 4, 5, 6];
22$grouped = Arrays::groupBy($numbers, fn($n) => $n % 2);
23// Returns: [
24//     1 => [1, 3, 5],  // odd numbers
25//     0 => [2, 4, 6]   // even numbers
26// ]
Parameter Type Description
$array array The array to group.
$groupBy `callable string`

Returns array — Returns an associative array where keys are group identifiers and values are arrays of items belonging to each group

See also

  • \Phuture\Coherence\Arrays::associate()
  • \Phuture\Coherence\Arrays::partition()

has()

public static function has(array $array, string|int|array $key): bool

Checks if a key exists in an array.

This method determines whether a specific key exists in an array. For nested arrays, you can pass an array of keys representing the path to check for existence.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$data = [
 4    'settings' => [
 5        'theme' => [
 6            'color' => 'blue'
 7        ]
 8    ],
 9    'active' => true
10];
11
12// Check simple key
13Arrays::has($data, 'active');
14// Returns: true
15
16// Check nested key using array path
17Arrays::has($data, ['settings', 'theme', 'color']);
18// Returns: true
19
20// Check non-existent key
21Arrays::has($data, 'missing');
22// Returns: false
23
24// Check non-existent nested key
25Arrays::has($data, ['settings', 'theme', 'font']);
26// Returns: false
Parameter Type Description
$array array The array to check for key existence
$key `string int

Returns bool — Returns true if the key exists, false otherwise

insertAfter()

public static function insertAfter(array &$array, string|int $key, array $items): void

Inserts elements after a specified key in an array.

This method inserts new key-value pairs into an array at a position immediately after the specified key.

If a key already exists, it remains unchanged. The array is modified by reference.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['first' => 10, 'second' => 20];
 4Arrays::insertAfter($array, 'first', ['hello' => 'world']);
 5// Result: ['first' => 10, 'hello' => 'world', 'second' => 20]
 6
 7// Insert after non-existent key (appends)
 8$array = ['first' => 10];
 9Arrays::insertAfter($array, 'missing', ['new' => 20]);
10// Result: ['first' => 10, 'new' => 20]
Parameter Type Description
$array array The array to insert into (passed by reference).
$key `string int`
$items array Associative array of key-value pairs to insert

See also

  • \Phuture\Coherence\Arrays::insertBefore()

insertBefore()

public static function insertBefore(array &$array, string|int $key, array $items): void

Inserts elements before a specified key in an array.

This method inserts new key-value pairs into an array at a position immediately before the specified key.

If a key already exists, it remains unchanged. The array is modified by reference.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['first' => 10, 'second' => 20];
 4Arrays::insertBefore($array, 'second', ['hello' => 'world']);
 5// Result: ['first' => 10, 'hello' => 'world', 'second' => 20]
 6
 7// Insert before non-existent key (prepends)
 8$array = ['first' => 10];
 9Arrays::insertBefore($array, 'missing', ['new' => 5]);
10// Result: ['new' => 5, 'first' => 10]
Parameter Type Description
$array array The array to insert into (passed by reference).
$key `string int`
$items array Associative array of key-value pairs to insert

See also

  • \Phuture\Coherence\Arrays::insertAfter()

intersect()

public static function intersect(array $array, ...$arrays): array

Returns elements that are present in all provided arrays.

This method compares values across multiple arrays and returns only those values that appear in every array. Keys are preserved from the first array.

You can optionally provide a custom comparison function as the last parameter.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic usage
 4$array1 = ['a', 'b', 'c', 'd'];
 5$array2 = ['b', 'c', 'e'];
 6$array3 = ['c', 'b', 'f'];
 7
 8$common = Arrays::intersect($array1, $array2, $array3);
 9// Returns: [1 => 'b', 2 => 'c'] (values present in all arrays)
10
11// With custom comparison function (case-insensitive)
12$array1 = ['Apple', 'Banana', 'Cherry'];
13$array2 = ['BANANA', 'cherry'];
14
15$result = Arrays::intersect(
16    $array1,
17    $array2,
18    fn($a, $b) => strcasecmp($a, $b)
19);
20// Returns: [1 => 'Banana', 2 => 'Cherry']
21
22// Comparing objects by property
23$users1 = [
24    (object)['id' => 1, 'name' => 'John'],
25    (object)['id' => 2, 'name' => 'Jane'],
26    (object)['id' => 3, 'name' => 'Bob']
27];
28$users2 = [
29    (object)['id' => 2, 'name' => 'Jane'],
30    (object)['id' => 4, 'name' => 'Alice']
31];
32
33$result = Arrays::intersect(
34    $users1,
35    $users2,
36    fn($a, $b) => $a->id <=> $b->id
37);
38// Returns: [1 => Jane object] (only user with id=2 exists in both)

Without a comparison callback the values are compared as strings, so every value must be scalar, null or stringable. Pass a comparison callback to intersect arrays holding nested arrays or objects that cannot be converted to a string.

Parameter Type Description
$array array The array to compare from.
...$arrays array Arrays to compare against
$callback `callable null`

Returns array — Returns values present in all arrays with keys preserved from the first array

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When no comparison array is provided, or when a value cannot be compared as a string and no comparison callback is given

See also

  • \Phuture\Coherence\Arrays::intersectAssoc()
  • \Phuture\Coherence\Arrays::intersectKeys()

intersectAssoc()

public static function intersectAssoc(array $array, ...$arrays): array

Returns elements that are present in all provided arrays, comparing both keys and values, with optional custom comparison.

This method is like intersect() but also checks that the keys match. An element is only included if both its key and value from the first array exist as a pair in all other arrays. You can provide custom comparison functions for values, keys, or both.

The method supports flexible parameter order where callbacks and the comparator can be provided at the end of the argument list.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2use Phuture\Coherence\Enum\ArrayComparator;
 3
 4// Basic usage
 5$array1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
 6$array2 = ['a' => 'apple', 'b' => 'banana', 'd' => 'date'];
 7$array3 = ['a' => 'apple', 'c' => 'coconut'];
 8$result = Arrays::intersectAssoc($array1, $array2, $array3);
 9// Returns: ['a' => 'apple']
10// (only key 'a' with value 'apple' exists in all arrays)
11
12// With custom value comparison and comparator
13$array1 = ['a' => 'Apple', 'b' => 'Banana'];
14$array2 = ['a' => 'APPLE', 'b' => 'orange'];
15$result = Arrays::intersectAssoc(
16    $array1,
17    $array2,
18    ArrayComparator::Value, // compare values using callback
19    fn($a, $b) => strcasecmp($a, $b) // callback for case-insensitive comparison
20);
21// Returns: ['a' => 'Apple']
22// (key 'a' with case-insensitive value 'apple' exists in both)
23
24// With custom key comparison
25$array1 = [1 => 'one', 2 => 'two', 3 => 'three'];
26$array2 = ['1' => 'one', '2' => 'two'];
27$result = Arrays::intersectAssoc(
28    $array1,
29    $array2,
30    ArrayComparator::Key, // compare keys using callback
31    fn($a, $b) => (string)$a <=> (string)$b // callback for key comparison
32);
33// Returns: [1 => 'one', 2 => 'two']
34// (keys 1 and 2 match when compared as strings)
35
36// With custom comparison for both keys and values
37$array1 = [1 => 'Apple', 2 => 'Banana'];
38$array2 = ['1' => 'APPLE', '2' => 'BANANA'];
39$result = Arrays::intersectAssoc(
40    $array1,
41    $array2,
42    ArrayComparator::Both, // compare both keys and values using callbacks
43    fn($a, $b) => strcasecmp($a, $b), // callback for value comparison
44    fn($a, $b) => (string)$a <=> (string)$b // callback for key comparison
45);
46// Returns: [1 => 'Apple', 2 => 'Banana']
47// (both key-value pairs match with custom comparisons)
Parameter Type Description
$array array The array to compare from.
...$arrays array Arrays to compare against
$comparator ArrayComparator The comparator to use with the provided callback(s) (required with callbacks)
$firstCallback `callable null`
$secondCallback `callable null`

Returns array — Returns key-value pairs present in all arrays

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When no comparison arrays are provided, when callbacks are provided without an ArrayComparator OR when more than two callbacks are provided
  • \Phuture\Coherence\Exception\LogicException — When no ArrayComparator enum is provided when needed OR when ArrayComparator::Both is not used with exactly two callbacks

See also

  • \Phuture\Coherence\Arrays::intersect()
  • \Phuture\Coherence\Arrays::intersectKeys()
  • \Phuture\Coherence\Enum\ArrayComparator

intersectKeys()

public static function intersectKeys(array $array, ...$arrays): array

Returns elements whose keys are present in all provided arrays.

This method compares only the keys (not values) across multiple arrays and returns key-value pairs from the first array whose keys appear in all other arrays. The values don't need to match, only the keys. You can optionally provide a custom comparison function for keys.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
 4$array2 = ['a' => 99, 'c' => 88, 'd' => 4];
 5$array3 = ['a' => 77, 'c' => 66];
 6
 7$result = Arrays::intersectKeys($array1, $array2, $array3);
 8// Returns: ['a' => 1, 'c' => 3]
 9// (keys 'a' and 'c' exist in all arrays, values from first array are kept)
10
11// With callback for type-insensitive key comparison
12$array1 = [1 => 'one', 2 => 'two', 3 => 'three'];
13$array2 = ['1' => 'ONE', '2' => 'TWO'];
14
15$result = Arrays::intersectKeys(
16    $array1,
17    $array2,
18    fn($a, $b) => (string)$a <=> (string)$b
19);
20// Returns: [1 => 'one', 2 => 'two']
21// (numeric keys 1 and 2 match string keys '1' and '2' when compared as strings)
Parameter Type Description
$array array The array to compare from.
...$arrays array Arrays to compare against
$callback `callable null`

Returns array — Returns key-value pairs whose keys are found in all arrays

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When no comparison array is provided

See also

  • \Phuture\Coherence\Arrays::intersect()

isAssoc()

public static function isAssoc(array $array): bool

Checks if the given array is an associative array.

An array is considered "associative" if it does not have sequential integer keys starting from 0. This method determines if an array is not a list, but rather has string keys or non-sequential numeric keys.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Returns true - has string keys
 4Arrays::isAssoc(['name' => 'John', 'age' => 30]);
 5
 6// Returns true - non-sequential numeric keys
 7Arrays::isAssoc([1 => 'first', 3 => 'third']);
 8
 9// Returns false - sequential numeric keys starting from 0
10Arrays::isAssoc([0 => 'first', 1 => 'second', 2 => 'third']);
Parameter Type Description
$array array The array to check.

Returns bool — Returns true if the array is associative, false if it's a list

See also

  • \Phuture\Coherence\Arrays::isList()

isBlank()

public static function isBlank(array $array): bool

Checks if the given array is empty (blank).

An array is considered "blank" if it contains no elements. This is a semantic wrapper around count($array) === 0 that provides more expressive intent in array operations.

Example:

1use Phuture\Coherence\Arrays;
2
3// Returns true - completely empty array
4Arrays::isBlank([]);
5
6// Returns false - contains elements, even if they're null or empty
7Arrays::isBlank([null, '', 0]);
8Arrays::isBlank(['name' => 'John']);
Parameter Type Description
$array array The array to check.

Returns bool — Returns true if the array is empty, false otherwise

See also

  • \Phuture\Coherence\Arrays::isFilled()

isFilled()

public static function isFilled(array $array): bool

Checks if the given array is not empty (filled).

An array is considered "filled" if it contains one or more elements. This method is the logical opposite of isBlank() and provides expressive intent when checking for non-empty arrays.

Example:

1use Phuture\Coherence\Arrays;
2
3// Returns true - contains elements, even if they're null or empty
4Arrays::isFilled([1, 2, 3]);
5Arrays::isFilled(['name' => 'John']);
6Arrays::isFilled([null, '', 0]);
7
8// Returns false - completely empty array
9Arrays::isFilled([]);
Parameter Type Description
$array array The array to check.

Returns bool — Returns true if the array is not empty, false otherwise

See also

  • \Phuture\Coherence\Arrays::isBlank()

isList()

public static function isList(array $array): bool

Checks whether a given array is a list.

This method determines if an array is a list, meaning it has sequential numeric keys starting from 0 with no gaps. A list has keys like [0, 1, 2, 3], whereas an associative array might have keys like ['name', 'age'] or [1, 3, 5].

Example:

1use Phuture\Coherence\Arrays;
2
3$list = ['apple', 'banana', 'cherry'];
4$isList = Arrays::isList($list);
5// Returns: true (keys are 0, 1, 2)
6
7$assoc = ['fruit' => 'apple', 'color' => 'red'];
8$isList = Arrays::isList($assoc);
9// Returns: false (has string keys)
Parameter Type Description
$array array The array to check.

Returns bool — Returns true if the array is a list, false otherwise

See also

  • \Phuture\Coherence\Arrays::isAssoc()

iterate()

public static function iterate(array|object &$array, callable $callback, bool $recursive = false, mixed $args = null): bool

Applies a user-defined function to every element of an array.

This method runs a custom function on each element in an array. You can modify the values by passing them by reference in your callback function. Optionally process nested arrays recursively to apply the function to all levels of a multidimensional array.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic iteration
 4$prices = [10, 20, 30];
 5Arrays::iterate($prices, function(&$value, $key) {
 6    $value = $value * 1.1; // Add 10% tax
 7});
 8// $prices is now: [11, 22, 33]
 9
10// Recursive iteration on nested arrays
11$data = [
12    'user' => ['name' => 'John', 'age' => 30],
13    'settings' => ['theme' => 'dark', 'notifications' => true]
14];
15Arrays::iterate($data, function(&$value, $key) {
16    if (is_string($value)) {
17        $value = strtoupper($value);
18    }
19}, true);
20// $data is now with all string values in uppercase
Parameter Type Description
$array `array object`
$callback callable The function to apply to each element The callback has the signature function (mixed $value, mixed $key): mixed
$recursive bool Whether to recursively process nested arrays (default: false)
$args mixed Optional additional data to pass to the callback function

Returns bool — Returns true on success, false on failure

keys()

public static function keys(array $array): array

Returns all the keys from an array.

This method extracts all keys from an array and returns them as a new indexed array. The keys can be strings, integers, or a mix of both. The resulting array will have numeric keys starting from 0.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 4$keys = Arrays::keys($array);
 5// Returns: ['name', 'email', 'age']
 6
 7// With numeric keys
 8$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];
 9$keys = Arrays::keys($numbers);
10// Returns: [10, 20, 30]
11
12// Mixed keys
13$mixed = ['a' => 1, 0 => 2, 'b' => 3];
14$keys = Arrays::keys($mixed);
15// Returns: ['a', 0, 'b']
Parameter Type Description
$array array The array from which to extract keys

Returns array — Returns an indexed array containing all keys from the input array

See also

  • \Phuture\Coherence\Arrays::values()

last()

public static function last(array $array): mixed

Returns the last value of an array.

This method retrieves the last value from an array without modifying it. The method throws an exception for empty arrays. This is useful for quickly accessing the last element without worrying about array keys or positions.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 4$last = Arrays::last($array);
 5// Returns: 30
 6
 7// With numeric array
 8$numbers = [10, 20, 30];
 9$last = Arrays::last($numbers);
10// Returns: 30
11
12// Empty array - throws exception
13$empty = [];
14$last = Arrays::last($empty);
15// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to get the last value from

Returns mixed — Returns the last value

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When the array is empty

See also

  • \Phuture\Coherence\Arrays::first()

lastKey()

public static function lastKey(array $array): string|int

Returns the last key of an array.

This method retrieves the last key from an array without modifying it. The method throws an exception for empty arrays. The key can be a string or integer.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 4$lastKey = Arrays::lastKey($array);
 5// Returns: 'age'
 6
 7// With numeric keys
 8$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];
 9$lastKey = Arrays::lastKey($numbers);
10// Returns: 30
11
12// Empty array - throws exception
13$empty = [];
14$lastKey = Arrays::lastKey($empty);
15// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to get the last key from

Returns string|int — Returns the last key

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When the array is empty

See also

  • \Phuture\Coherence\Arrays::firstKey()

length()

public static function length(array $array, CountMode $mode = CountMode::Normal): int

Counts all elements in an array.

This method returns the total number of elements in an array. By default, it counts only the elements in the top level. You can optionally count all elements recursively in a multidimensional array to get the total count of all nested elements.

Example:

 1use Phuture\Coherence\Arrays;
 2use Phuture\Coherence\Enum\CountMode;
 3
 4$fruits = ['apple', 'banana', 'cherry'];
 5$count = Arrays::length($fruits);
 6
 7// Returns: 3
 8
 9$nested = ['a', 'b', ['c', 'd', 'e']];
10$total = Arrays::length($nested, CountMode::Recursive);
11
12// Returns: 6 (counts all nested elements)
Parameter Type Description
$array array The array to count elements in
$mode \Phuture\Coherence\Enum\CountMode The counting mode — Normal or Recursive (default: CountMode::Normal)

Returns int — The number of elements in the array

See also

  • \Phuture\Coherence\Enum\CountMode

map()

public static function map(array $array, callable $callback): array

Maps an array to a new structure using a callback that determines the values.

This method transforms array values by applying a callback function to each value, while preserving the keys. The callback receives the value as its argument and should return the transformed value.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['apple', 'banana', 'cherry'];
 4
 5// Convert values to uppercase
 6$result = Arrays::map($array, fn($value) => strtoupper($value));
 7// Returns: ['APPLE', 'BANANA', 'CHERRY']
 8
 9// Double numeric values
10$numbers = [1, 2, 3, 4, 5];
11$result = Arrays::map($numbers, fn($n) => $n * 2);
12// Returns: [2, 4, 6, 8, 10]
13
14// Extract property from objects
15$users = [
16    (object)['name' => 'John', 'age' => 30],
17    (object)['name' => 'Jane', 'age' => 25]
18];
19$result = Arrays::map($users, fn($user) => $user->name);
20// Returns: ['John', 'Jane']
Parameter Type Description
$array array The array whose values to transform
$callback callable The callback function to apply to each value The callback has the signature function (mixed $value): mixed

Returns array — Returns a new array with transformed values and original keys

See also

  • \Phuture\Coherence\Arrays::mapKeys()
  • \Phuture\Coherence\Arrays::mapWithKeys()
  • \Phuture\Coherence\Arrays::reduce()

mapKeys()

public static function mapKeys(array $array, callable $callback): array

Maps an array to a new structure using a callback that determines the keys.

This method transforms array keys by applying a callback function to each key, while preserving the values. The callback receives the key as its argument and should return the new key.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['first_name' => 'John', 'last_name' => 'Doe'];
 4
 5// Convert keys to uppercase
 6$result = Arrays::mapKeys($array, fn($key) => strtoupper($key));
 7// Returns: ['FIRST_NAME' => 'John', 'LAST_NAME' => 'Doe']
 8
 9// Prefix all keys
10$result = Arrays::mapKeys($array, fn($key) => 'user_' . $key);
11// Returns: ['user_first_name' => 'John', 'user_last_name' => 'Doe']
Parameter Type Description
$array array The array whose keys to transform
$callback callable The callback function to apply to each key The callback has the signature function (mixed $key): mixed

Returns array — Returns a new array with transformed keys and original values

See also

  • \Phuture\Coherence\Arrays::map()
  • \Phuture\Coherence\Arrays::mapWithKeys()

mapWithKeys()

public static function mapWithKeys(array $array, callable $callback): array

Maps an array to a new structure using a callback that determines both keys and values.

This method iterates through an array and applies a callback function to each element. Unlike map() which transforms only values, or mapKeys() which transforms only keys, this method allows you to completely restructure the array by determining both the new key and new value for each element. This is useful for restructuring data or creating lookup tables from complex data structures.

The callback receives both the value and its key, and should return an associative array with exactly one key-value pair that becomes part of the new array.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    ['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
 5    ['id' => 2, 'name' => 'Jane', 'email' => '[email protected]']
 6];
 7
 8// Create lookup table with ID as key and email as value
 9$lookup = Arrays::mapWithKeys($users, fn($user) => [$user['id'] => $user['email']]);
10// Returns: [1 => '[email protected]', 2 => '[email protected]']
11
12// Transform to associative array with custom key-value structure
13$result = Arrays::mapWithKeys($users, fn($user) => [$user['name'] => $user['id']]);
14// Returns: ['John' => 1, 'Jane' => 2]
15
16// Use both value and key in transformation
17$data = ['a' => 10, 'b' => 20, 'c' => 30];
18$result = Arrays::mapWithKeys($data, fn($value, $key) => [strtoupper($key) => $value * 2]);
19// Returns: ['A' => 20, 'B' => 40, 'C' => 60]
20
21// Handle duplicate keys (later elements overwrite earlier ones)
22$numbers = [1, 2, 3];
23$result = Arrays::mapWithKeys($numbers, fn($num) => ['all' => $num]);
24// Returns: ['all' => 3] (3 overwrites 1 and 2)
Parameter Type Description
$array array The array to map to a new structure
$callback callable A function that receives ($value, $key) and returns an array with one key-value pair The callback has the signature function (mixed $value, mixed $key): array

Returns array — Returns a new array with the structure defined by the callback

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When the callback doesn't return an array with exactly one element

See also

  • \Phuture\Coherence\Arrays::map()
  • \Phuture\Coherence\Arrays::mapKeys()

median()

public static function median(array $array): ?float

Calculates the median (middle value) of values in an array.

This method finds the middle value in a sorted list of numbers. The median is useful because it's not affected by extremely high or low values the way an average is. Think of it like finding the value that splits your data in half.

For an odd number of elements, the median is the middle value. For an even number of elements, the median is the average of the two middle values.

If the array is empty, this method returns null.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Odd number of elements - returns middle value
 4$numbers = [1, 3, 5];
 5$med = Arrays::median($numbers);
 6
 7// Returns: 3
 8
 9// Even number of elements - returns average of two middle values
10$numbers = [1, 2, 3, 4];
11$med = Arrays::median($numbers);
12
13// Returns: 2.5
14
15// Unsorted input gets sorted automatically
16$numbers = [5, 1, 3, 2, 4];
17$med = Arrays::median($numbers);
18
19// Returns: 3
20
21// Empty array returns null
22$med = Arrays::median([]);
23
24// Returns: null
Parameter Type Description
$array array The array containing numeric values

Returns float|null — The median value, or null if the array is empty

See also

  • \Phuture\Coherence\Arrays::average()

merge()

public static function merge(...$arrays): array

Combines multiple arrays into one.

This method merges two or more arrays into a single array. Numeric keys are renumbered from 0; string keys are preserved. By default (shallow merge), if the same string key appears in multiple arrays the later value wins. Pass true as the last argument to enable recursive (deep) merging — nested arrays with the same key are merged together instead of overwritten, and duplicate scalar values under the same key are combined into an array.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$a = ['a' => 'apple', 'b' => 'banana'];
 4$b = ['b' => 'blueberry', 'c' => 'cherry'];
 5
 6// Shallow merge (default) — later value overwrites
 7Arrays::merge($a, $b);
 8// Returns: ['a' => 'apple', 'b' => 'blueberry', 'c' => 'cherry']
 9
10// Recursive merge — nested arrays are deep-merged
11$cfg1 = ['db' => ['host' => 'localhost', 'port' => 3306]];
12$cfg2 = ['db' => ['user' => 'admin']];
13Arrays::merge($cfg1, $cfg2, true);
14// Returns: ['db' => ['host' => 'localhost', 'port' => 3306, 'user' => 'admin']]
Parameter Type Description
...$arrays array Two or more arrays to merge together
$recursive bool Whether to deep-merge nested arrays instead of overwriting (default: false)

Returns array — Returns a new merged array

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When fewer than 2 arrays or any is empty

See also

  • \Phuture\Coherence\Arrays::collapse()

normalize()

public static function normalize(array $array): array

Normalizes a multidimensional array by converting all objects to arrays.

This method recursively processes an array and converts any objects (like stdClass) into plain arrays. This is useful when you need to work with data that might contain mixed object and array structures, such as JSON data that was decoded with object conversion, or database results that return objects.

The method produces the same result as using json_decode(json_encode($array), true) but is more efficient and doesn't have the limitations of JSON encoding.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$obj = new stdClass();
 4$obj->name = 'John';
 5$obj->address = new stdClass();
 6$obj->address->city = 'NYC';
 7
 8$mixed = [
 9    'user' => $obj,
10    'active' => true
11];
12
13$normalized = Arrays::normalize($mixed);
14
15// Returns: [
16//     'user' => [
17//         'name' => 'John',
18//         'address' => ['city' => 'NYC']
19//     ],
20//     'active' => true
21// ]
Parameter Type Description
$array array The array to normalize, which may contain objects

Returns array — Returns a pure array with all objects converted to arrays

See also

  • \Phuture\Coherence\Arrays::toObject()

notation()

public static function notation(array $array, string $prefix = ''): array

Flattens a multidimensional array into a single-level array using dot notation.

This method takes a nested array (arrays within arrays) and converts it into a flat array where the keys represent the path to each value using dots as separators. For example, if you have a value at ['user']['name'], it becomes 'user.name' in the flattened array.

Empty arrays are treated as leaf values and preserved in the output.

This is useful for configuration arrays, deeply nested data structures, or when you need to convert complex arrays into a simple list format.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$nested = [
 4    'name' => 'John',
 5    'address' => [
 6        'city' => 'NYC',
 7        'zip' => '10001'
 8    ]
 9];
10$flat = Arrays::notation($nested);
11
12// Returns: ['name' => 'John', 'address.city' => 'NYC', 'address.zip' => '10001']
13
14// Empty arrays are preserved
15$data = ['key' => 'value', 'empty' => []];
16$flat = Arrays::notation($data);
17// Returns: ['key' => 'value', 'empty' => []]
Parameter Type Description
$array array The multidimensional array to flatten
$prefix string Optional prefix to prepend to all keys (for internal recursion)

Returns array — Returns a flattened single-level array with dot notation keys

See also

  • \Phuture\Coherence\Arrays::denote()

of()

public static function of(array $array): Type\Arrays

Creates a fluent wrapper for array manipulation with method chaining.

This method wraps an array in a Types\Arrays instance, which enables fluent method chaining for array operations. Instead of calling static methods one at a time, you can chain multiple operations together and call get() or toArray() at the end to retrieve the final result.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Using fluent chaining (chainable methods return arrays)
 4$result = Arrays::of([1, 2, 3, 4, 5])
 5    ->filter(fn($v) => $v > 2) // Returns array - chainable
 6    ->reverse() // Returns array - chainable
 7    ->values() // Returns array - chainable
 8    ->get();
 9// Returns: [5, 4, 3]
10
11// Equivalent to calling static methods individually:
12$filtered = Arrays::filter([1, 2, 3, 4, 5], fn($v) => $v > 2);
13$reversed = Arrays::reverse($filtered);
14$result = Arrays::values($reversed);
15// Alternative methods
16$users = [
17    ['name' => 'John', 'age' => 30],
18    ['name' => 'Jane', 'age' => 25],
19    ['name' => 'Bob', 'age' => 35]
20];
21// You can also use toArray to get the final result
22$names = Arrays::of($users)
23    ->column('name')
24    ->toArray();
25// Returns: ['John', 'Jane', 'Bob']
26
27// Or, call the object as a function to get the final result
28$names = Arrays::of($users)
29    ->column('name')();
30// Returns: ['John', 'Jane', 'Bob']
31
32// Or, use the object as an array
33$names = Arrays::of($users)
34    ->column('name');
35$name = $names[0];
36// Returns 'John'
Parameter Type Description
$array array The array to wrap for fluent operations

Returns Type\Arrays — A fluent wrapper instance that enables method chaining

See also

  • \Phuture\Coherence\Type\Arrays — For the fluent wrapper implementation

only()

public static function only(array $array, array $keys): array

Gets a subset of the items from the given array.

This method returns a new array containing only the items whose keys are specified in the $keys parameter. Keys that don't exist in the original array will be ignored. This is useful when you need to extract specific fields from a larger data structure.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$user = [
 4    'id' => 1,
 5    'name' => 'John Doe',
 6    'email' => '[email protected]',
 7    'password' => 'secret',
 8    'created_at' => '2023-01-01'
 9];
10// Extract only specific fields
11$safeUser = Arrays::only($user, ['id', 'name', 'email']);
12// Result: ['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]']
13
14// Keys that don't exist are ignored
15$partial = Arrays::only($user, ['id', 'name', 'nonexistent']);
16// Result: ['id' => 1, 'name' => 'John Doe']
17
18// Empty keys array returns empty array
19$empty = Arrays::only($user, []);
20// Result: []
Parameter Type Description
$array array The original array to extract items from
$keys array The list of keys to extract from the array

Returns array — A new array containing only the specified keys and their values

pad()

public static function pad(array $array, int $length, mixed $value): array

Pads an array to the specified length with a given value.

This method fills an array to a specified length by adding elements with the given value. If the length is positive, padding is added to the right (end) of the array. If negative, padding is added to the left (beginning). The absolute value of the length determines the final size of the array. If the length is smaller than or equal to the current array size, no padding occurs.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Pad to the right
 4$array = [1, 2, 3];
 5$result = Arrays::pad($array, 5, 0);
 6// Returns: [1, 2, 3, 0, 0]
 7
 8// Pad to the left
 9$array = [1, 2, 3];
10$result = Arrays::pad($array, -5, 0);
11// Returns: [0, 0, 1, 2, 3]
12
13// No padding when length <= current size
14$array = [1, 2, 3];
15$result = Arrays::pad($array, 3, 0);
16// Returns: [1, 2, 3]
17
18// Padding associative arrays
19$array = ['name' => 'John', 'age' => 30];
20$result = Arrays::pad($array, 4, null);
21// Returns: ['name' => 'John', 'age' => 30, 0 => null, 1 => null]
Parameter Type Description
$array array The input array to pad
$length int The desired length; positive pads right, negative pads left
$value mixed The value to use for padding

Returns array — Returns the padded array

partition()

public static function partition(array $array, callable $callback): array

Splits an array into two groups based on a callback function.

This method separates items into those that pass a test and those that fail. The first array in the returned pair contains all items where the callback returns true, and the second array contains all items where it returns false.

Think of it like sorting coins into two piles: one for heads and one for tails. Both piles preserve which coins came from which position in the original pile.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$numbers = [1, 2, 3, 4, 5, 6];
 4
 5// Partition into even and odd
 6[$even, $odd] = Arrays::partition($numbers, fn($n) => $n % 2 === 0);
 7// $even contains: [2, 4, 6]
 8// $odd contains: [1, 3, 5]
 9
10// Partition associative array
11$users = [
12    'user1' => ['active' => true],
13    'user2' => ['active' => false],
14    'user3' => ['active' => true]
15];
16[$active, $inactive] = Arrays::partition($users, fn($user) => $user['active']);
17// $active contains: ['user1' => [...], 'user3' => [...]]
18// $inactive contains: ['user2' => [...]]
Parameter Type Description
$array array The array to partition.
$callback callable Function that returns true for the first array, false for the second. The callback has the signature function (mixed $value, mixed $key): bool

Returns array — Returns an array with two elements: [passing_items, failing_items]

See also

  • \Phuture\Coherence\Arrays::groupBy()
  • \Phuture\Coherence\Arrays::filter()

prepend()

public static function prepend(array &$array, array $items): void

Prepends key-value pairs to an array.

This method prepends new key-value pairs to the beginning of an array. If keys already exist, they will be overwritten. The array is modified by reference.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John'];
 4Arrays::prepend($array, ['age' => 30, 'city' => 'NYC']);
 5// Result: ['age' => 30, 'city' => 'NYC', 'name' => 'John']
 6
 7$array = ['name' => 'John', 'age' => null];
 8Arrays::prepend($array, ['age' => 30, 'city' => 'NYC']);
 9// Result: ['age' => 30, 'city' => 'NYC', 'name' => 'John']
10
11$array = [];
12Arrays::prepend($array, ['user' => 'demo', 'email' => '[email protected]']);
13// Result: ['user' => 'demo', 'email' => '[email protected]']
Parameter Type Description
$array array The array to add key-value pairs to (passed by reference)
$items array Associative array of key-value pairs to prepend

See also

  • \Phuture\Coherence\Arrays::append()

product()

public static function product(array $array): int|float

Calculates the product of the values in the array.

This method multiplies all the numbers in an array together and returns the result. If the array contains non-numeric values, they are treated as zero.

Example:

1use Phuture\Coherence\Arrays;
2
3$numbers = [2, 3, 4];
4$result = Arrays::product($numbers);
5
6// Returns: 24 (2 * 3 * 4)
Parameter Type Description
$array array The array containing values to multiply

Returns int|float — The product of all values in the array

See also

  • \Phuture\Coherence\Arrays::sum()

pull()

public static function pull(array &$array): mixed

Removes and returns the last element from the end of the array.

This method removes the last element from an array and returns it. The array is modified by reference, meaning the original array is shortened by one element. If the array is empty, an exception is thrown. This is commonly used for implementing stack data structures (LIFO - Last In, First Out) or removing the most recently added item.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Remove last element
 4$stack = ['first', 'second', 'third'];
 5$last = Arrays::pull($stack);
 6// $last contains: 'third'
 7// $stack is now: ['first', 'second']
 8
 9// With associative arrays
10$data = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
11$last = Arrays::pull($data);
12// $last contains: 30
13// $data is now: ['name' => 'John', 'email' => '[email protected]']
14
15// Empty array throws exception
16$empty = [];
17$result = Arrays::pull($empty);
18// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to remove the last element from (passed by reference)

Returns mixed — Returns the last element

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — If the array is empty

See also

  • \Phuture\Coherence\Arrays::push()
  • \Phuture\Coherence\Arrays::shift()

push()

public static function push(array &$array, mixed ...$values): int

Adds one or more elements to the end of an array.

This method appends one or more values to the end of an array. The array is modified by reference, meaning the original array grows in size. The method returns the new total number of elements in the array. This is commonly used for implementing stack data structures (LIFO - Last In, First Out) or building arrays dynamically.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Add single element
 4$stack = ['first', 'second'];
 5$count = Arrays::push($stack, 'third');
 6// $count is: 3
 7// $stack is now: ['first', 'second', 'third']
 8
 9// Add multiple elements
10$items = ['apple'];
11$count = Arrays::push($items, 'banana', 'cherry', 'date');
12// $count is: 4
13// $items is now: ['apple', 'banana', 'cherry', 'date']
14
15// With associative arrays (adds with numeric keys)
16$data = ['name' => 'John'];
17Arrays::push($data, 'extra value');
18// $data is now: ['name' => 'John', 0 => 'extra value']
Parameter Type Description
$array array The array to add elements to (passed by reference)
...$values mixed One or more values to add to the end

Returns int — Returns the new number of elements in the array

See also

  • \Phuture\Coherence\Arrays::pull()
  • \Phuture\Coherence\Arrays::unshift()

random()

public static function random(array $array): mixed

Returns a random value from an array.

This method selects one element at random from an array and returns its value. Each element has an equal probability of being selected. This is useful for selecting random items from a list, implementing random features, or shuffling data for testing purposes.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Get random fruit
 4$fruits = ['apple', 'banana', 'cherry', 'date'];
 5$random = Arrays::random($fruits);
 6// Returns: one of the fruits (e.g., 'cherry')
 7
 8// With associative arrays
 9$colors = ['red' => '#FF0000', 'green' => '#00FF00', 'blue' => '#0000FF'];
10$randomColor = Arrays::random($colors);
11// Returns: one of the color codes (e.g., '#00FF00')
12
13// Single element array always returns that element
14$single = ['only'];
15$result = Arrays::random($single);
16// Returns: 'only'
Parameter Type Description
$array array The array to pick a random value from

Returns mixed — Returns a randomly selected value from the array

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When array is empty

See also

  • \Phuture\Coherence\Arrays::randomKeys()
  • \Phuture\Coherence\Arrays::shuffle()

randomKeys()

public static function randomKeys(array $array, int $num = 1): string|int|array

Picks one or more random keys from an array.

This method selects one or more keys at random from an array and returns them. When selecting a single key, it returns a string or integer. When selecting multiple keys, it returns an array of keys. Each key has an equal probability of being selected, and the same key will not be selected twice.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Get one random key (default)
 4$data = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 5$randomKey = Arrays::randomKeys($data);
 6// Returns: one of the keys (e.g., 'email')
 7
 8// Get multiple random keys
 9$data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
10$randomKeys = Arrays::randomKeys($data, 3);
11// Returns: an array of 3 keys (e.g., ['b', 'd', 'a'])
12
13// With numeric keys
14$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];
15$keys = Arrays::randomKeys($numbers, 2);
16// Returns: an array of 2 numeric keys (e.g., [20, 10])
Parameter Type Description
$array array The array to pick random keys from
$num int The number of keys to select (default: 1)

Returns string|int|array — Returns a single key if $num is 1, or an array of keys if $num > 1

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When array is empty or num is less than 1 or greater than array size

See also

  • \Phuture\Coherence\Arrays::random()

reduce()

public static function reduce(array $array, callable $callback, mixed $initial = null): mixed

Iteratively reduces an array to a single value using a callback function.

This method processes each element in an array through a callback function to accumulate a single result value. The callback receives two parameters: the accumulated result (carry) and the current element. You can optionally provide an initial value to start the accumulation. This is useful for summing values, building strings, flattening arrays, or any operation that combines array elements into a single output.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Sum all numbers
 4$numbers = [1, 2, 3, 4, 5];
 5$sum = Arrays::reduce($numbers, fn($carry, $item) => $carry + $item, 0);
 6// Returns: 15
 7
 8// Concatenate strings
 9$words = ['Hello', 'beautiful', 'world'];
10$sentence = Arrays::reduce($words, fn($carry, $word) => $carry . ' ' . $word, '');
11// Returns: ' Hello beautiful world'
12
13// Build an associative array
14$items = [['id' => 1, 'name' => 'Apple'], ['id' => 2, 'name' => 'Banana']];
15$lookup = Arrays::reduce(
16    $items,
17    fn($carry, $item) => $carry + [$item['id'] => $item['name']],
18    []
19);
20// Returns: [1 => 'Apple', 2 => 'Banana']
21
22// Calculate product
23$numbers = [2, 3, 4];
24$product = Arrays::reduce($numbers, fn($carry, $item) => $carry * $item, 1);
25// Returns: 24
Parameter Type Description
$array array The array to reduce
$callback callable Function that receives ($carry, $item) and returns the new carry value The callback has the signature function (mixed $carry, mixed $item): mixed
$initial mixed Optional initial value for the carry (default: null)

Returns mixed — Returns the final accumulated value

See also

  • \Phuture\Coherence\Arrays::map()
  • \Phuture\Coherence\Arrays::filter()

remove()

public static function remove(array &$array, string|int|array $key): void

Removes a key-value pair from an array.

This method removes a key from an array, including deeply nested keys by passing an array path. The array is modified by reference, meaning the original array is changed directly.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$data = [
 4    'config' => [
 5        'database' => [
 6            'host' => 'localhost',
 7            'port' => 3306
 8        ]
 9    ],
10    'debug' => true
11];
12
13// Remove simple key
14Arrays::remove($data, 'debug');
15// Result: ['config' => [...]]
16
17// Remove nested key using array path
18Arrays::remove($data, ['config', 'database', 'port']);
19// Result: ['config' => ['database' => ['host' => 'localhost']]]
Parameter Type Description
$array array The array to remove the key from (passed by reference)
$key `string int

rename()

public static function rename(array &$array, string|int|array $oldKey, string|int $newKey): void

Renames a key in an array.

This method renames an existing key to a new name while preserving the value and key order. The array is modified by reference. If the old key doesn't exist, an exception is thrown. For nested arrays, you can pass an array path where the last element is the key to rename.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$data = [
 4    'first_name' => 'John',
 5    'last_name' => 'Doe',
 6    'age' => 30
 7];
 8
 9// Rename simple key
10Arrays::rename($data, 'first_name', 'firstName');
11// Result: ['firstName' => 'John', 'last_name' => 'Doe', 'age' => 30]
12
13// Rename nested key using array path
14$config = [
15    'database' => [
16        'db_host' => 'localhost',
17        'db_port' => 3306
18    ]
19];
20Arrays::rename($config, ['database', 'db_host'], 'host');
21// Result: ['database' => ['host' => 'localhost', 'db_port' => 3306]]
22
23// Trying to rename non-existent key throws exception
24Arrays::rename($data, 'missing', 'new');
25// Throws: OutOfBoundsException
Parameter Type Description
$array array The array containing the key to rename (passed by reference)
$oldKey `string int
$newKey `string int`

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When the old key doesn't exist

replace()

public static function replace(array $array, bool $recursive = false, array ...$replacements): array

Replaces elements from passed arrays into the first array.

This method replaces values in the first array with values from subsequent arrays based on matching keys. Elements with matching keys in later arrays overwrite those in earlier arrays. When recursive mode is enabled, the method will also traverse nested arrays and perform replacement operations recursively. This is useful for merging configuration arrays, updating settings, or applying default values while preserving structure.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic replacement
 4$base = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
 5$replacement = ['b' => 'blueberry', 'c' => 'coconut'];
 6$result = Arrays::replace($base, false, $replacement);
 7// Returns: ['a' => 'apple', 'b' => 'blueberry', 'c' => 'coconut']
 8
 9// Recursive replacement
10$base = ['user' => ['name' => 'John', 'email' => '[email protected]']];
11$replacement = ['user' => ['email' => '[email protected]']];
12$result = Arrays::replace($base, true, $replacement);
13// Returns: ['user' => ['name' => 'John', 'email' => '[email protected]']]
14
15// Multiple replacement arrays
16$base = ['a' => 1, 'b' => 2];
17$result = Arrays::replace($base, false, ['b' => 3], ['c' => 4]);
18// Returns: ['a' => 1, 'b' => 3, 'c' => 4]
Parameter Type Description
$array array The base array whose elements will be replaced
$recursive bool Whether to recursively replace nested arrays (default: false)
...$replacements array One or more arrays containing replacement values

Returns array — Returns the modified array with replaced values

reverse()

public static function reverse(array $array, bool $preserveKeys = false): array

Returns an array with elements in reverse order.

This method reverses the order of elements in an array. The first element becomes the last, and the last element becomes the first. By default, numeric keys are renumbered starting from 0, while string keys are always preserved. Set the preserveKeys parameter to true to maintain the original numeric key associations.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Numeric keys are renumbered (default behavior)
 4$array = ['first', 'second', 'third'];
 5$result = Arrays::reverse($array);
 6// Returns: ['third', 'second', 'first']
 7
 8// Preserves string keys (default behavior)
 9$array = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
10$result = Arrays::reverse($array);
11// Returns: ['c' => 'cherry', 'b' => 'banana', 'a' => 'apple']
12
13// With key preservation (maintains numeric keys)
14$array = ['first', 'second', 'third'];
15$result = Arrays::reverse($array, true);
16// Returns: [2 => 'third', 1 => 'second', 0 => 'first']
17
18// With key preservation (mixed keys)
19$array = [0 => 'zero', 'name' => 'John', 1 => 'one'];
20$result = Arrays::reverse($array, true);
21// Returns: [1 => 'one', 'name' => 'John', 0 => 'zero']
Parameter Type Description
$array array The array to reverse
$preserveKeys bool Whether to preserve numeric keys (default: false)

Returns array — Returns a new array with elements in reverse order

public static function search(array $array, mixed $needle, bool $strict = false): int|string|false

Searches the array for a given value and returns the first corresponding key if successful.

This method looks through an array for a specific value and returns the key of the first match found. If the value is not found, it returns false. By default, it uses loose comparison, but you can enable strict comparison to check both value and type. This is useful for finding the position or key of a value in an array.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic search
 4$fruits = ['apple', 'banana', 'cherry', 'date'];
 5$key = Arrays::search($fruits, 'cherry');
 6// Returns: 2
 7
 8// With associative arrays
 9$data = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
10$key = Arrays::search($data, '[email protected]');
11// Returns: 'email'
12
13// Value not found
14$key = Arrays::search($fruits, 'mango');
15// Returns: false
16
17// Loose vs strict comparison
18$numbers = [1, 2, 3, '4', 5];
19$key = Arrays::search($numbers, 4); // Loose comparison
20// Returns: 3 (finds '4' as a string)
21$key = Arrays::search($numbers, 4, true); // Strict comparison
22// Returns: false (4 !== '4')
Parameter Type Description
$array array The array to search
$needle mixed The value to search for
$strict bool Whether to use strict comparison (default: false)

Returns int|string|false — Returns the key of the first match, or false if not found

See also

  • \Phuture\Coherence\Arrays::find()

shift()

public static function shift(array &$array): mixed

Removes and returns the first element from the beginning of the array.

This method removes the first element from an array and returns it. The array is modified by reference, meaning the original array is shortened by one element and all remaining elements are shifted down. Numeric keys are re-indexed starting from 0, while string keys remain unchanged. If the array is empty, it returns null. This is commonly used for implementing queue data structures (FIFO - First In, First Out).

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Remove first element
 4$queue = ['first', 'second', 'third'];
 5$first = Arrays::shift($queue);
 6// $first contains: 'first'
 7// $queue is now: ['second', 'third'] (reindexed to [0 => 'second', 1 => 'third'])
 8
 9// With associative arrays
10$data = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
11$first = Arrays::shift($data);
12// $first contains: 'John'
13// $data is now: ['email' => '[email protected]', 'age' => 30]
14
15// Empty array throws exception
16$empty = [];
17$result = Arrays::shift($empty);
18// Throws: OutOfBoundsException
Parameter Type Description
$array array The array to remove the first element from (passed by reference)

Returns mixed — Returns the first element

Throws

  • \Phuture\Coherence\Exception\OutOfBoundsException — When array is empty

See also

  • \Phuture\Coherence\Arrays::unshift()
  • \Phuture\Coherence\Arrays::pull()

shuffle()

public static function shuffle(array &$array): bool

Shuffles an array randomly.

This method randomly rearranges the order of elements in an array. Each time you run it, the elements will be in a different random order. The original array keys are replaced with sequential numeric keys starting from 0.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic card shuffle
 4$cards = ['Ace', 'King', 'Queen', 'Jack'];
 5Arrays::shuffle($cards);
 6// $cards might now be: ['Queen', 'Ace', 'Jack', 'King']
 7
 8// Practical use case: random quiz questions
 9$questions = [
10    'What is 2 + 2?',
11    'What is the capital of France?',
12    'Who wrote Romeo and Juliet?',
13    'What is H2O?'
14];
15Arrays::shuffle($questions);
16// Now questions appear in random order for each quiz attempt
17
18// Creating a random password from character sets
19$chars = ['a', 'b', 'c', '1', '2', '3', '!', '@', '#'];
20Arrays::shuffle($chars);
21$password = implode('', array_slice($chars, 0, 6));
22// Generates random 6-character password
Parameter Type Description
$array array The array to shuffle (passed by reference)

Returns bool — Returns true on success, false on failure

slice()

public static function slice(array $array, int $offset, ?int $length = null, bool $preserveKeys = false): array

Extracts a slice of an array.

This method returns a portion of an array starting at a specified offset and continuing for a given length. The original array is not modified. You can use negative offsets to count from the end of the array. By default, numeric keys are re-indexed starting from 0, but you can preserve the original keys by setting preserveKeys to true.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['a', 'b', 'c', 'd', 'e'];
 4
 5// Extract middle portion
 6$slice = Arrays::slice($array, 2, 2);
 7// Returns: ['c', 'd']
 8
 9// Start from position 1, take rest of array
10$slice = Arrays::slice($array, 1);
11// Returns: ['b', 'c', 'd', 'e']
12
13// Negative offset (count from end)
14$slice = Arrays::slice($array, -2);
15// Returns: ['d', 'e']
16
17// Preserve keys
18$slice = Arrays::slice($array, 1, 3, true);
19// Returns: [1 => 'b', 2 => 'c', 3 => 'd']
20
21// With associative arrays (keys always preserved)
22$data = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
23$slice = Arrays::slice($data, 1, 1);
24// Returns: ['email' => '[email protected]']
Parameter Type Description
$array array The input array to extract from
$offset int The starting position (negative counts from end)
$length `int null`
$preserveKeys bool Whether to preserve numeric keys (default: false)

Returns array — Returns the extracted portion of the array

See also

  • \Phuture\Coherence\Arrays::splice()

some()

public static function some(array $array, callable $callback): bool

Checks if at least one array element satisfies a callback function.

This method tests elements in an array against a condition you provide. It returns true if AT LEAST ONE element passes the test. Think of it like checking if anyone in a group has completed their homework.

Example:

1use Phuture\Coherence\Arrays;
2
3$numbers = [1, 3, 5, 8];
4$hasEven = Arrays::any($numbers, fn($n) => $n % 2 === 0);
5// Returns: true (8 is even)
6
7$ages = [16, 15, 14];
8$hasAdult = Arrays::any($ages, fn($age) => $age >= 18);
9// Returns: false (none are 18 or older)
Parameter Type Description
$array array The array whose elements to test.
$callback callable A function that receives each element and returns true if it passes the test The callback has the signature function (mixed $value, mixed $key): bool

Returns bool — Returns true if ANY element passes the callback test, false if none pass

See also

  • \Phuture\Coherence\Arrays::every()

sort()

public static function sort(array &$array, bool $reverse = false, ?callable $callback = null): bool

Sorts an array in ascending or descending order with optional index preservation.

This method arranges array values from lowest to highest (ascending) or highest to lowest (descending). You can provide a custom comparison function to define your own sorting logic. Note that array keys are not preserved - elements are re-indexed with sequential numeric keys starting from 0.

You can optionally provide a custom comparison function as the last parameter.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$numbers = [5, 2, 8, 1, 9];
 4Arrays::sort($numbers);
 5// $numbers is now: [1, 2, 5, 8, 9]
 6
 7// Sort in reverse (descending) order
 8Arrays::sort($numbers, true);
 9// $numbers is now: [9, 8, 5, 2, 1]
10
11// Sort with custom callback (case-insensitive string comparison)
12$words = ['Apple', 'banana', 'Cherry', 'date'];
13Arrays::sort($words, false, fn($a, $b) => strcasecmp($a, $b));
14// $words is now: ['Apple', 'banana', 'Cherry', 'date']
15
16// Sort objects by property
17$users = [
18    (object)['name' => 'John', 'age' => 30],
19    (object)['name' => 'Jane', 'age' => 25],
20    (object)['name' => 'Bob', 'age' => 35]
21];
22Arrays::sort($users, false, fn($a, $b) => $a->age <=> $b->age);
23// Sorted by age: Jane (25), John (30), Bob (35)
24
25// Sort with callback in reverse
26Arrays::sort($users, true, fn($a, $b) => strcmp($a->name, $b->name));
27// Sorted by name descending: John, Jane, Bob
Parameter Type Description
$array array The array to sort (passed by reference)
$reverse bool Whether to sort in descending order (default: false)
$callback `callable null`

Returns bool — Returns true on success, false on failure

See also

  • \Phuture\Coherence\Arrays::sortKeys()
  • \Phuture\Coherence\Arrays::sortAssoc()
  • \Phuture\Coherence\Arrays::sortNatural()
  • \Phuture\Coherence\Arrays::sortBy()

sortAssoc()

public static function sortAssoc(array &$array, bool $reverse = false, ?callable $callback = null): bool

Sorts an array in ascending or descending order while maintaining index association.

This method arranges array values from lowest to highest (ascending) or highest to lowest (descending) while keeping the original keys paired with their values. Unlike the regular sort method, this preserves the relationship between keys and values. You can provide a custom comparison function to define your own sorting logic.

You can optionally provide a custom comparison function as the last parameter.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$scores = ['John' => 85, 'Alice' => 92, 'Bob' => 78];
 4Arrays::sortAssoc($scores);
 5// $scores is now: ['Bob' => 78, 'John' => 85, 'Alice' => 92]
 6// Keys are preserved with their values
 7
 8// Sort with custom callback (case-insensitive string comparison)
 9$names = ['john' => 'John', 'ALICE' => 'Alice', 'bob' => 'Bob'];
10Arrays::sortAssoc($names, false, fn($a, $b) => strcasecmp($a, $b));
11// $names is now: ['ALICE' => 'Alice', 'bob' => 'Bob', 'john' => 'John']
12
13// Sort objects by property while preserving keys
14$users = [
15    'user1' => (object)['name' => 'John', 'age' => 30],
16    'user2' => (object)['name' => 'Jane', 'age' => 25],
17    'user3' => (object)['name' => 'Bob', 'age' => 35]
18];
19Arrays::sortAssoc($users, false, fn($a, $b) => $a->age <=> $b->age);
20// Sorted by age: user2 => Jane (25), user1 => John (30), user3 => Bob (35)
21
22// Sort with callback in reverse
23$prices = ['item1' => 100, 'item2' => 50, 'item3' => 75];
24Arrays::sortAssoc($prices, true, fn($a, $b) => $a <=> $b);
25// $prices is now: ['item1' => 100, 'item3' => 75, 'item2' => 50]
Parameter Type Description
$array array The array to sort (passed by reference)
$reverse bool Whether to sort in descending order (default: false)
$callback `callable null`

Returns bool — Returns true on success, false on failure

See also

  • \Phuture\Coherence\Arrays::sort()

sortBy()

public static function sortBy(array &$array, string|array|callable $criteria, bool $reverse = false, int $flags = 0): bool

Sorts an array by a given key or multiple keys.

This method sorts a multidimensional array (array of arrays or objects) by one or more keys. You can sort by a single key, multiple keys for multi-level sorting, or provide a custom callback to determine the sort value. The original keys are not preserved - the array is re-indexed.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Sort by a single key
 4$users = [
 5    ['name' => 'John', 'age' => 30],
 6    ['name' => 'Alice', 'age' => 25],
 7    ['name' => 'Bob', 'age' => 35]
 8];
 9Arrays::sortBy($users, 'age');
10// Result: [
11//     ['name' => 'Alice', 'age' => 25],
12//     ['name' => 'John', 'age' => 30],
13//     ['name' => 'Bob', 'age' => 35]
14// ]
15
16// Sort by multiple keys (age ascending, then name descending)
17Arrays::sortBy($users, ['age', 'name']);
18// First sorts by age, then for equal ages, sorts by name
19
20// Sort in descending order
21Arrays::sortBy($users, 'age', true);
22// Result: [
23//     ['name' => 'Bob', 'age' => 35],
24//     ['name' => 'John', 'age' => 30],
25//     ['name' => 'Alice', 'age' => 25]
26// ]
27
28// Sort array of objects by property
29$products = [
30    (object)['name' => 'Apple', 'price' => 1.50],
31    (object)['name' => 'Banana', 'price' => 0.75],
32    (object)['name' => 'Cherry', 'price' => 2.00]
33];
34Arrays::sortBy($products, 'price');
35// Sorted by price ascending
36
37// Sort with custom callback for complex sorting
38$words = ['apple', 'Banana', 'CHERRY', 'date'];
39Arrays::sortBy($words, fn($item) => strtolower($item));
40// Case-insensitive sort
Parameter Type Description
$array array The array to sort (passed by reference)
$criteria `string array
$reverse bool Whether to sort in descending order (default: false)
$flags int Sort flags for natural sorting (optional, e.g., SORT_NATURAL)

Returns bool — Returns true on success, false on failure

See also

  • \Phuture\Coherence\Arrays::sort()
  • \Phuture\Coherence\Arrays::sortAssoc()
  • \Phuture\Coherence\Arrays::sortKeys()

sortKeys()

public static function sortKeys(array &$array, bool $reverse = false, ?callable $callback = null): bool

Sorts an array by keys in ascending or descending order.

This method arranges an array based on its keys rather than its values. Keys are sorted from lowest to highest (ascending) or highest to lowest (descending). The association between keys and values is maintained. You can provide a custom comparison function to define your own sorting logic for the keys.

You can optionally provide a custom comparison function as the last parameter.

The callback for the comparison function has the signature function (mixed $a, mixed $b): int

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$ages = ['John' => 25, 'Alice' => 30, 'Bob' => 20];
 4Arrays::sortKeys($ages);
 5// $ages is now: ['Alice' => 30, 'Bob' => 20, 'John' => 25]
 6
 7// Sort keys in reverse order
 8$ages = ['John' => 25, 'Alice' => 30, 'Bob' => 20];
 9Arrays::sortKeys($ages, true);
10// $ages is now: ['John' => 25, 'Bob' => 20, 'Alice' => 30]
11
12// Sort with custom callback (case-insensitive key comparison)
13$data = ['name' => 'John', 'AGE' => 30, 'Email' => '[email protected]'];
14Arrays::sortKeys($data, false, fn($a, $b) => strcasecmp($a, $b));
15// $data is now: ['AGE' => 30, 'Email' => '[email protected]', 'name' => 'John']
16
17// Sort keys by length
18$items = ['aaa' => 1, 'b' => 2, 'cc' => 3];
19Arrays::sortKeys($items, false, fn($a, $b) => strlen($a) - strlen($b));
20// $items is now: ['b' => 2, 'cc' => 3, 'aaa' => 1]
21
22// Sort numeric string keys as integers
23$numbers = ['10' => 'ten', '2' => 'two', '1' => 'one'];
24Arrays::sortKeys($numbers, false, fn($a, $b) => (int)$a - (int)$b);
25// $numbers is now: ['1' => 'one', '2' => 'two', '10' => 'ten']
Parameter Type Description
$array array The array to sort by keys (passed by reference)
$reverse bool Whether to sort in descending order (default: false)
$callback `callable null`

Returns bool — Returns true on success, false on failure

See also

  • \Phuture\Coherence\Arrays::sort()

sortNatural()

public static function sortNatural(array &$array, bool $caseInsensitive = false): bool

Sorts an array using natural order algorithm.

This method sorts strings in the way a human would naturally order them, which is especially useful for sorting filenames or version numbers. For example, it will sort "file2.txt" before "file10.txt" (whereas a regular sort would put "file10.txt" first). Optionally ignore letter case when sorting.

Example:

1use Phuture\Coherence\Arrays;
2
3$files = ['file10.txt', 'file2.txt', 'file1.txt', 'file20.txt'];
4Arrays::sortNatural($files);
5
6// $files is now: ['file1.txt', 'file2.txt', 'file10.txt', 'file20.txt']
7// Notice that file2.txt comes before file10.txt
Parameter Type Description
$array array The array to sort (passed by reference)
$caseInsensitive bool Whether to ignore case when sorting (default: false)

Returns bool — Returns true on success, false on failure

See also

  • \Phuture\Coherence\Arrays::sort()

splice()

public static function splice(array &$array, int $offset, ?int $length = null, mixed $replacement = []): array

Removes a portion of an array and optionally replaces it with new elements.

This method removes elements from an array starting at a specified offset and continuing for a given length, then optionally inserts replacement elements at that position. The array is modified by reference. The method returns an array containing the removed elements. This is useful for inserting, removing, or replacing elements in the middle of an array.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Remove elements
 4$array = ['a', 'b', 'c', 'd', 'e'];
 5$removed = Arrays::splice($array, 2, 2);
 6// $removed contains: ['c', 'd']
 7// $array is now: ['a', 'b', 'e']
 8
 9// Remove and replace
10$array = ['a', 'b', 'c', 'd', 'e'];
11$removed = Arrays::splice($array, 2, 2, ['X', 'Y', 'Z']);
12// $removed contains: ['c', 'd']
13// $array is now: ['a', 'b', 'X', 'Y', 'Z', 'e']
14
15// Insert without removing (length = 0)
16$array = ['a', 'b', 'e'];
17Arrays::splice($array, 2, 0, ['c', 'd']);
18// $array is now: ['a', 'b', 'c', 'd', 'e']
19
20// Remove from position to end
21$array = ['a', 'b', 'c', 'd', 'e'];
22Arrays::splice($array, 2);
23// $array is now: ['a', 'b']
Parameter Type Description
$array array The array to modify (passed by reference)
$offset int The starting position (negative counts from end)
$length `int null`
$replacement mixed Elements to insert at the offset position (default: empty array)

Returns array — Returns an array containing the removed elements

See also

  • \Phuture\Coherence\Arrays::slice()

split()

public static function split(array $array, int $length, bool $preserveKeys = false): array

Splits an array into chunks of a specified size.

This method divides an array into smaller arrays (chunks) of a specified length. The last chunk may contain fewer elements if the array doesn't divide evenly. By default, numeric keys are re-indexed within each chunk starting from 0, but you can preserve the original keys by setting preserveKeys to true.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Basic chunking
 4$array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
 5$chunks = Arrays::split($array, 3);
 6// Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
 7
 8// Preserve keys
 9$array = [1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd'];
10$chunks = Arrays::split($array, 2, true);
11// Returns: [[1 => 'a', 2 => 'b'], [3 => 'c', 4 => 'd']]
12
13// With associative arrays (keys always preserved)
14$data = ['name' => 'John', 'email' => '[email protected]', 'age' => 30, 'city' => 'NYC'];
15$chunks = Arrays::split($data, 2);
16// Returns: [['name' => 'John', 'email' => '[email protected]'], ['age' => 30, 'city' => 'NYC']]
17
18// Processing in batches
19$items = range(1, 100);
20$batches = Arrays::split($items, 25);
21// Returns: 4 arrays of 25 items each
Parameter Type Description
$array array The array to split into chunks
$length int The size of each chunk (must be greater than 0)
$preserveKeys bool Whether to preserve array keys (default: false)

Returns array — Returns a multidimensional array of chunks

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — If length is less than 1

See also

  • \Phuture\Coherence\Arrays::join()

sum()

public static function sum(array $array): int|float

Calculates the sum of values in an array.

This method adds up all the numbers in an array and returns the total. If the array contains non-numeric values, they are treated as zero.

Example:

1use Phuture\Coherence\Arrays;
2
3$numbers = [1, 2, 3, 4, 5];
4$total = Arrays::sum($numbers);
5
6// Returns: 15
Parameter Type Description
$array array The array containing values to sum

Returns int|float — The sum of all values in the array

See also

  • \Phuture\Coherence\Arrays::product()
  • \Phuture\Coherence\Arrays::reduce()

toArray()

public static function toArray(mixed $value): array

This method converts various input types into an array.

It supports various data types to arrays using smart conversion rules. It handles objects with toArray() or toJson() methods, JsonSerializable objects, existing arrays, scalar values, and JSON strings. User-defined classes that are not anonymous are serialized using DeepClone, which preserves private and protected properties, nested objects, and object references.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// From object with toArray method
 4$obj = new class { public function toArray() { return ['a' => 1]; } };
 5$result = Arrays::toArray($obj);
 6// Returns: ['a' => 1]
 7
 8// From object with toJson method
 9$obj = new class { public function toJson() { return '{"b": 2}'; } };
10$result = Arrays::toArray($obj);
11// Returns: ['b' => 2]
12
13// From JsonSerializable
14$obj = new class implements \JsonSerializable {
15    public function jsonSerialize() { return ['c' => 3]; }
16};
17$result = Arrays::toArray($obj);
18// Returns: ['c' => 3]
19
20// From existing array
21$result = Arrays::toArray([1, 2, 3]);
22// Returns: [1, 2, 3]
23
24// From scalar values
25$result = Arrays::toArray('hello');
26// Returns: ['hello']
27
28$result = Arrays::toArray(42);
29// Returns: [42]
30
31// From null
32$result = Arrays::toArray(null);
33// Returns: []
34
35// From stdClass
36$obj = new \stdClass();
37$obj->name = 'John';
38$result = Arrays::toArray($obj);
39// Returns: ['name' => 'John']
40
41// From JSON string
42$result = Arrays::toArray('{"name": "Jane", "age": 25}');
43// Returns: ['name' => 'Jane', 'age' => 25]
Parameter Type Description
$value mixed The value to convert to array

Returns array — Returns the converted array

See also

  • \Phuture\Coherence\Arrays::toObject()

toJson()

public static function toJson(array $array): string

Converts an array to a JSON string.

This method encodes an array into its JSON string representation, which can be used for storage, transmission, or interoperability with other systems and APIs.

Example:

1use Phuture\Coherence\Arrays;
2
3$array = ['name' => 'John', 'age' => 30];
4$json = Arrays::toJson($array);
5
6// Returns: '{"name":"John","age":30}'
Parameter Type Description
$array array The array to encode as JSON

Returns string — The JSON-encoded string representation of the array

See also

  • \Phuture\Coherence\Arrays::toObject()

toObject()

public static function toObject(array $array): object

Converts associative arrays to objects recursively, leaving lists untouched.

This method transforms an associative array and all its nested associative arrays into stdClass objects. List arrays (indexed arrays without string keys) are preserved as arrays and not converted to objects. This is the opposite of the normalize() method, which converts objects to arrays.

When the given array contains DeepClone serialization data (as produced by toArray() for user-defined classes), this method will rebuild the original object with all its private and protected properties, nested objects, and references intact. If the array is not valid DeepClone data, it falls back to converting the array to a stdClass object.

This is useful when you need to work with object notation for accessing nested data structures, especially when dealing with JSON data or configuration that you want to access with arrow syntax (->) instead of bracket notation ([]).

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Simple array to object
 4$array = ['name' => 'John', 'age' => 30];
 5$obj = Arrays::toObject($array);
 6// Returns: { name: "John", age: 30 }
 7
 8// Multidimensional array to objects
 9$data = [
10    'user' => [
11        'name' => 'Jane',
12        'address' => [
13            'street' => '123 Main St',
14            'city' => 'NYC'
15        ]
16    ],
17    'settings' => ['theme' => 'dark']
18];
19$obj = Arrays::toObject($data);
20// Returns:
21// {
22//     user: {
23//         name: "Jane",
24//         address: { street: "123 Main St", city: "NYC" }
25//     },
26//     settings: { theme: "dark" }
27// }
28
29// Accessing properties
30echo $obj->user->name; // Outputs: Jane
31echo $obj->user->address->city; // Outputs: NYC
32
33// Lists are preserved as arrays
34$data = [
35    'user' => 'John',
36    'tags' => ['php', 'arrays', 'objects']  // list array
37];
38$obj = Arrays::toObject($data);
39// Returns: { user: "John", tags: ["php", "arrays", "objects"] }
40// Note: tags remains an array, not converted to object
Parameter Type Description
$array array The array to convert to objects, which may contain nested arrays

Returns object — Returns a stdClass object with associative arrays converted to objects and lists preserved

See also

  • \Phuture\Coherence\Arrays::toArray()
  • \Phuture\Coherence\Arrays::normalize()

unique()

public static function unique(array $array, SortComparison $comparison = SortComparison::String): array

Removes duplicate values from an array.

This method filters an array to keep only unique values, removing any duplicates. If the same value appears multiple times, only the first occurrence is kept. The array keys are preserved from the original array.

Example:

 1use Phuture\Coherence\Arrays;
 2use Phuture\Coherence\Enum\SortComparison;
 3
 4$colors = ['red', 'blue', 'red', 'green', 'blue'];
 5$uniqueColors = Arrays::unique($colors);
 6
 7// Returns: ['red', 'blue', 'green']
 8
 9$numbers = ['1', 1, '1.0', 2];
10$uniqueNumbers = Arrays::unique($numbers, SortComparison::Numeric);
11
12// Returns: ['1', 2]
Parameter Type Description
$array array The array to remove duplicates from
$comparison \Phuture\Coherence\Enum\SortComparison How values are compared to detect duplicates — Regular, Numeric, String or LocaleString (default: SortComparison::String)

Returns array — Returns an array with unique values

See also

  • \Phuture\Coherence\Enum\SortComparison

unshift()

public static function unshift(array &$array, mixed ...$values): int

Prepends one or more elements to the beginning of an array.

This method adds one or more values to the start of an array. The array is modified by reference, meaning the original array grows in size and all existing elements are shifted up. The method returns the new total number of elements in the array. Numeric keys are re-indexed starting from 0, while string keys remain unchanged. This is commonly used for implementing queue data structures (FIFO - First In, First Out).

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Add single element to beginning
 4$queue = ['second', 'third'];
 5$count = Arrays::unshift($queue, 'first');
 6// $count is: 3
 7// $queue is now: ['first', 'second', 'third']
 8
 9// Add multiple elements
10$items = ['cherry'];
11$count = Arrays::unshift($items, 'apple', 'banana');
12// $count is: 3
13// $items is now: ['apple', 'banana', 'cherry']
14
15// With associative arrays (string keys preserved, numeric reindexed)
16$data = ['email' => '[email protected]', 'age' => 30];
17Arrays::unshift($data, 'John');
18// $data is now: [0 => 'John', 'email' => '[email protected]', 'age' => 30]
Parameter Type Description
$array array The array to add elements to (passed by reference)
...$values mixed One or more values to add to the beginning

Returns int — Returns the new number of elements in the array

See also

  • \Phuture\Coherence\Arrays::shift()
  • \Phuture\Coherence\Arrays::push()

values()

public static function values(array $array): array

Returns all values from an array.

This method extracts all values from an array and returns them as a new indexed array with numeric keys starting from 0. This effectively removes all the original keys and re-indexes the array sequentially.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$array = ['name' => 'John', 'email' => '[email protected]', 'age' => 30];
 4$values = Arrays::values($array);
 5// Returns: ['John', '[email protected]', 30]
 6
 7// With numeric keys
 8$numbers = [10 => 'ten', 20 => 'twenty', 30 => 'thirty'];
 9$values = Arrays::values($numbers);
10// Returns: ['ten', 'twenty', 'thirty']
11
12// Already indexed array (no change)
13$indexed = ['apple', 'banana', 'cherry'];
14$values = Arrays::values($indexed);
15// Returns: ['apple', 'banana', 'cherry']
Parameter Type Description
$array array The array from which to extract values

Returns array — Returns an indexed array containing all values from the input array

See also

  • \Phuture\Coherence\Arrays::keys()

where()

public static function where(array $array, callable $callback): array

Filters an array using a callback function.

This method creates a new array containing only the elements that pass a test you provide. It is an alias for the filter method with a clearer name for predicate-based filtering scenarios.

Use this method when you want to find items that match specific conditions, like finding all products above a certain price or all users with a certain status.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    ['name' => 'John', 'age' => 25, 'active' => true],
 5    ['name' => 'Jane', 'age' => 17, 'active' => true],
 6    ['name' => 'Bob', 'age' => 30, 'active' => false]
 7];
 8
 9// Find adults (age 18+)
10$adults = Arrays::where($users, fn($user) => $user['age'] >= 18);
11// Returns: [
12//     ['name' => 'John', 'age' => 25, 'active' => true],
13//     ['name' => 'Bob', 'age' => 30, 'active' => false]
14// ]
15
16// Find active users
17$active = Arrays::where($users, fn($user) => $user['active']);
18// Returns: [
19//     ['name' => 'John', 'age' => 25, 'active' => true],
20//     ['name' => 'Jane', 'age' => 17, 'active' => true]
21// ]
Parameter Type Description
$array array The array to filter.
$callback callable Function that tests each element, returns true to keep it The callback has the signature function (mixed $value, mixed $key): bool

Returns array — Returns a new array containing only the elements that pass the test

See also

  • \Phuture\Coherence\Arrays::filter()
  • \Phuture\Coherence\Arrays::whereIn()
  • \Phuture\Coherence\Arrays::grep()

whereIn()

public static function whereIn(array $array, string $key, array $values): array

Filters an array where a key's value is in a given list of values.

This method filters an array to only include items where a specific key has a value that matches one of the values you provide. This is useful when you want to find items that belong to a certain category or match any of several possible values.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3$users = [
 4    ['id' => 1, 'name' => 'John', 'role' => 'admin'],
 5    ['id' => 2, 'name' => 'Jane', 'role' => 'user'],
 6    ['id' => 3, 'name' => 'Bob', 'role' => 'admin'],
 7    ['id' => 4, 'name' => 'Alice', 'role' => 'moderator']
 8];
 9
10// Find admins and moderators
11$privileged = Arrays::whereIn($users, 'role', ['admin', 'moderator']);
12// Returns: [
13//     ['id' => 1, 'name' => 'John', 'role' => 'admin'],
14//     ['id' => 3, 'name' => 'Bob', 'role' => 'admin'],
15//     ['id' => 4, 'name' => 'Alice', 'role' => 'moderator']
16// ]
Parameter Type Description
$array array The array to filter.
$key string The key to check in each array item.
$values array The list of values to match against.

Returns array — Returns a new array containing only items where the key's value is in the values list

See also

  • \Phuture\Coherence\Arrays::where()
  • \Phuture\Coherence\Arrays::filter()

wrap()

public static function wrap(array $array, string $prefix = '', string $suffix = ''): array

Wraps scalar elements by surrounding them with prefix and suffix strings.

This method processes each element in the array and wraps only scalar values (strings, integers, floats, booleans, null) by converting them to strings and surrounding them with the specified prefix and suffix. Non-scalar values like arrays, objects, and resources are left unchanged. The original array keys are preserved.

This is useful for formatting output, adding HTML tags to text values, or preparing strings for display while preserving complex data structures within the array.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Add HTML tags to strings
 4$colors = ['red', 'green', 'blue'];
 5$result = Arrays::wrap($colors, '<b>', '</b>');
 6// Returns: ['<b>red</b>', '<b>green</b>', '<b>blue</b>']
 7
 8// Mixed types - only scalars are wrapped
 9$mixed = ['text', 123, ['nested'], new stdClass(), true];
10$result = Arrays::wrap($mixed, '[', ']');
11// Returns: ['[text]', '[123]', ['nested'], stdClass object, '[1]']
12
13// Preserve keys
14$data = ['a' => 'red', 'b' => 'green'];
15$result = Arrays::wrap($data, '<<', '>>');
16// Returns: ['a' => '<<red>>', 'b' => '<<green>>']
17
18// Numbers are converted to strings
19$numbers = [1, 2, 3];
20$result = Arrays::wrap($numbers, '(', ')');
21// Returns: ['(1)', '(2)', '(3)']
Parameter Type Description
$array array The array whose scalar elements to wrap
$prefix string The string to prepend to each scalar element (default: empty string)
$suffix string The string to append to each scalar element (default: empty string)

Returns array — Returns a new array with wrapped scalar elements and preserved keys

zip()

public static function zip(array ...$arrays): array

Combines multiple arrays by pairing elements at the same index.

This method takes multiple arrays and creates a new array where each element is an array containing the corresponding elements from each input array at that position. Think of it like zipping together two jacket halves - the teeth from each side pair up at the same position.

If the arrays have different lengths, the shortest length determines the number of pairs produced. Extra elements in longer arrays are ignored.

Example:

 1use Phuture\Coherence\Arrays;
 2
 3// Pair two arrays
 4$numbers = [1, 2, 3];
 5$letters = ['a', 'b', 'c'];
 6$zipped = Arrays::zip($numbers, $letters);
 7// Returns: [[1, 'a'], [2, 'b'], [3, 'c']]
 8
 9// Zip three arrays
10$ids = [1, 2];
11$names = ['John', 'Jane'];
12$ages = [30, 25];
13$zipped = Arrays::zip($ids, $names, $ages);
14// Returns: [[1, 'John', 30], [2, 'Jane', 25]]
15
16// Different lengths - uses shortest
17$a = [1, 2, 3, 4];
18$b = ['a', 'b'];
19$zipped = Arrays::zip($a, $b);
20// Returns: [[1, 'a'], [2, 'b']]
21
22// Create associative arrays
23$keys = ['name', 'age'];
24$values = ['John', 30];
25$zipped = Arrays::zip($keys, $values);
26// Returns: [['name', 'John'], ['age', 30]]
Parameter Type Description
...$arrays array Variable number of arrays to zip together

Returns array — Returns an array of paired elements from each input array

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — If fewer than two arrays are provided

See also

  • \Phuture\Coherence\Arrays::unzip()

assertStringComparable()

private static function assertStringComparable(array ...$arrays): void

Asserts that every value in the given arrays can be compared as a string.

The native intersection functions compare values by casting them to strings, which is undefined for nested arrays and for objects without a __toString() method. PHP 8.6 also changed when that conversion happens, so the inputs are validated up front to keep the behaviour identical across versions.

Parameter Type Description
...$arrays array The arrays whose values must be comparable as strings

Throws

  • \Phuture\Coherence\Exception\InvalidArgumentException — When a value cannot be converted to a string

flattenToNotation()

private static function flattenToNotation(array $array, string $prefix, array &$result, int $depth = 0): void

Recursively flattens a multidimensional array using dot notation keys.

This private helper method traverses through nested arrays, building dot-separated keys that represent the path to each value. For example, ['user' => ['name' => 'John']] becomes ['user.name' => 'John']. The method protects against infinite recursion by enforcing the RECURSION_LIMIT constant.

Parameter Type Description
$array array The multidimensional array to flatten.
$prefix string The current key prefix for nested elements (starts empty).
$result array The result array passed by reference where flattened key-value pairs are stored.
$depth int Current recursion depth to prevent stack overflow.

Throws

  • \Phuture\Coherence\Exception\LogicException — When recursion depth exceeds RECURSION_LIMIT to prevent stack overflow.

normalizeRecursive()

private static function normalizeRecursive(array $array, array &$result, int $depth = 0): void

Recursively normalizes an array by converting all objects to arrays.

This private helper method traverses through nested arrays and objects, converting any objects to their array representation while preserving the overall structure. This ensures that the entire data structure becomes a pure multidimensional array. The method protects against infinite recursion by enforcing the RECURSION_LIMIT constant.

Parameter Type Description
$array array The array to normalize (may contain objects).
$result array The result array passed by reference containing only array values.
$depth int Current recursion depth to prevent stack overflow.

Throws

  • \Phuture\Coherence\Exception\LogicException — When recursion depth exceeds RECURSION_LIMIT to prevent stack overflow.

toObjectRecursive()

private static function toObjectRecursive(array $array, stdClass &$result, int $depth = 0): void

Recursively converts arrays to stdClass objects.

This private helper method transforms a multidimensional array into a nested object structure where each array becomes a stdClass instance. This is useful for converting array-based data structures into object-based ones while preserving the nested hierarchy. The method protects against infinite recursion by enforcing the RECURSION_LIMIT constant.

Parameter Type Description
$array array The array to convert (may contain nested arrays).
$result stdClass The result object passed by reference containing the converted structure.
$depth int Current recursion depth to prevent stack overflow.

Throws

  • \Phuture\Coherence\Exception\LogicException — When recursion depth exceeds RECURSION_LIMIT to prevent stack overflow.