Oihana PHP

arrays

Table of Contents

Classes

CleanFlag
Enumeration representing cleaning modes as bit flags.

Functions

clean()  : array<string|int, mixed>
Cleans an array by removing unwanted values based on bitwise flags from the `CleanFlag` enum.
compress()  : array<string|int, mixed>
Compresses the given array by removing values that match one or more conditions.
deepMerge()  : array<string|int, mixed>
Recursively merges multiple arrays.
delete()  : mixed
Unset a key or nested key in an array using dot notation.
ensureArrayPath()  : array<string|int, mixed>
Ensures that a given key in an array contains a sub-array, and returns it by reference.
exists()  : bool
Checks whether a key exists in an array or an object implementing ArrayAccess.
flatten()  : array<string|int, mixed>
Flattens a nested array into a single-level array.
get()  : mixed
Retrieves a value from an associative array using a key path.
getFirstKey()  : mixed
Returns the first key from the provided list of keys that exists in the given array.
getFirstValue()  : mixed
Returns the value of the first key from the provided list of keys that exists in the given array.
hasIntKeys()  : bool
Indicates if all the keys in an array are integers.
hasStringKeys()  : bool
Indicates if all the keys in an array are strings.
inBetween()  : array<string|int, mixed>
Insert an element between all the items in an array.
isAssociative()  : bool
Determines if an array is associative.
isIndexed()  : bool
Determines if an array is indexed (i.e., has sequential integer keys starting at 0).
removeKeys()  : array<string|int, mixed>
Removes a set of keys from an array.
set()  : array<string|int, mixed>
Sets a value in an associative array using a key path.
setArrayValue()  : array<string|int, mixed>
Sets a value in a flat associative array using a single key.
shuffle()  : array<string|int, mixed>
Shuffles the elements of an array in place using the Fisher-Yates algorithm.
stub()  : array<string|int, mixed>
Returns a new empty array.
swap()  : array<string|int, mixed>
Swaps two indexed values in a specific array representation.
tail()  : array<string|int, mixed>
Returns a new array containing all elements except the first one.
toArray()  : array<string|int, mixed>
Ensures the given value is returned as an array.
unique()  : array<string|int, mixed>
Removes duplicate values from an array and reindexes it.

Functions

clean()

Cleans an array by removing unwanted values based on bitwise flags from the `CleanFlag` enum.

clean([array<string|int, mixed> $array = [] ][, int $flags = CleanFlag::DEFAULT ]) : array<string|int, mixed>

This function allows flexible and recursive filtering of arrays. Cleaning behavior is fully customizable via bitwise flags.

Supported flags from CleanFlag:

  • CleanFlag::NULLS : Removes null values.
  • CleanFlag::EMPTY : Removes empty strings ('').
  • CleanFlag::TRIM : Trims strings and treats whitespace-only strings as empty.
  • CleanFlag::EMPTY_ARR : Removes empty arrays (after recursive cleaning).
  • CleanFlag::RECURSIVE : Cleans nested arrays recursively.
  • CleanFlag::FALSY : Removes all PHP falsy values (null, '', 0, 0.0, '0', false, []).
  • CleanFlag::MAIN : Shortcut for enabling all the main flags: NULLS | EMPTY | EMPTY_ARR | TRIM.

Default behavior

Using CleanFlag::DEFAULT is equivalent to enabling:

CleanFlag::NULLS | CleanFlag::EMPTY | CleanFlag::TRIM | CleanFlag::EMPTY_ARR | CleanFlag::RECURSIVE

That means by default, clean() removes:

  • null
  • empty strings
  • strings containing only spaces/tabs/newlines
  • empty arrays
  • and also cleans nested arrays recursively.
Parameters
$array : array<string|int, mixed> = []

The input array to clean. Nested arrays are processed only if CleanFlag::RECURSIVE is set.

$flags : int = CleanFlag::DEFAULT

A bitmask of CleanFlag values. Defaults to CleanFlag::DEFAULT.

Tags
example

1. Basic cleaning: remove nulls and empty strings

use oihana\core\arrays\{clean, CleanFlag};

$data   = ['foo', '', null, 'bar'];
$result = clean($data, CleanFlag::NULLS | CleanFlag::EMPTY);
// ['foo', 'bar']

2. Remove whitespace-only strings as well

$data   = ['foo', '   ', '', null, 'bar'];
$result = clean($data, CleanFlag::NULLS | CleanFlag::EMPTY | CleanFlag::TRIM);
// ['foo', 'bar']

3. Recursive cleaning of nested arrays

$data = [
    'users' => [
        ['name' => '', 'email' => 'bob@example.com'],
        ['name' => 'Alice', 'email' => '']
    ]
];

$result = clean($data, CleanFlag::RECURSIVE | CleanFlag::EMPTY);
// [
//     'users' => [
//         ['email' => 'bob@example.com'],
//         ['name' => 'Alice']
//     ]
// ]

4. Remove empty arrays after recursive cleaning

$data = [
    'group1' => [],
    'group2' => [['name' => 'Alice'], []]
];

$result = clean($data, CleanFlag::RECURSIVE | CleanFlag::EMPTY_ARR);
// [
//     'group2' => [['name' => 'Alice']]
// ]

5. Remove all falsy values at once

$data   = [0, '', null, false, 'ok', [], '0'];
$result = clean($data, CleanFlag::FALSY);
// ['ok']

6. Full cleaning using default flags

$result = clean($data);
// Equivalent to CleanFlag::DEFAULT
see
CleanFlag

For available cleaning flags and default behavior.

see
isIndexed()

To determine if an array is numerically indexed.

author

Marc Alcaraz

since
1.0.6
Return values
array<string|int, mixed>

The filtered array:

  • Associative arrays: keys are preserved.
  • Indexed arrays: automatically reindexed to remove numeric gaps.

compress()

Compresses the given array by removing values that match one or more conditions.

compress(array<string|int, mixed> $array[, array<string|int, mixed>|null $options = [] ][, int $currentDepth = 0 ]) : array<string|int, mixed>

Useful for cleaning up associative arrays (e.g., from form submissions or object exports) by removing nulls, empty strings, or other unwanted values. Supports recursion into nested arrays or objects.

Parameters
$array : array<string|int, mixed>

The input array to compress.

$options : array<string|int, mixed>|null = []

Optional configuration:

  • clone (bool) If true, works on a cloned copy of the array. Original remains unchanged. (default: false)
  • conditions (callable|array) One or more callbacks: (mixed $value): bool. If any condition returns true, the value is removed. ( default: fn($v) => is_null($v) )*
  • excludes (string[]) List of keys to exclude from filtering, even if matched by a condition.
  • recursive (bool) Whether to recursively compress nested arrays or objects. (default: true)
  • depth (int|null) Maximum depth for recursion. null means no limit.
  • throwable (bool) If true, throws InvalidArgumentException for invalid conditions. (default: true)
$currentDepth : int = 0

(Internal) Tracks current recursion depth. You usually don’t need to set this.

Tags
example

Basic cleanup of null values

use function oihana\core\arrays\compress;
$data = ['id' => 1, 'name' => 'hello', 'description' => null];
$clean = compress($data);
// Result: ['id' => 1, 'name' => 'hello']

Exclude a specific key from filtering

$data = ['id' => 1, 'name' => null];
$clean = compress($data, ['excludes' => ['name']]);
// Result: ['id' => 1, 'name' => null]  // "name" is preserved

Remove null or empty strings

$conditions =
[
    fn($v) => is_null($v),
    fn($v) => is_string($v) && $v === ''
];
$data  = ['a' => '', 'b' => 0, 'c' => null];
$clean = compress($data, ['conditions' => $conditions]);
// Result: ['b' => 0]

Recursive compression with depth limit

$nested =
[
    'id'   => 2,
    'meta' => ['created' => null, 'tags' => []],
];

$clean = compress($nested,
[
    'conditions' => fn($v) => $v === [] || $v === null,
    'depth'      => 1
]);
// Result: ['id' => 2]

Clone input before compressing

$original = ['x' => null, 'y' => 5];
$copy     = compress($original, ['clone' => true]);
// $original remains unchanged; $copy == ['y' => 5]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The compressed array (or its clone if clone=true).

deepMerge()

Recursively merges multiple arrays.

deepMerge(array<string|int, mixed> ...$arrays) : array<string|int, mixed>
  • Associative keys (strings) are merged deeply : sub-arrays are merged récursivement.
  • Numeric keys (ints) are appended, maintaining order.
Parameters
$arrays : array<string|int, mixed>

The arrays to be merged.

Tags
example
$a = ['user' => ['name' => 'Alice', 'roles' => ['admin']]];
$b = ['user' => ['roles' => ['editor'], 'active' => true]];
$c = ['tags' => ['php', 'dev']];

$merged = deepMerge($a, $b, $c);

print_r($merged);
// [
//     'user' => [
//         'name'   => 'Alice',
//         'roles'  => ['admin', 'editor'],
//         'active' => true
//     ],
//     'tags' => ['php', 'dev']
// ]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The deeply merged array.

delete()

Unset a key or nested key in an array using dot notation.

delete(mixed $target, string|array<string|int, mixed> $key[, string $separator = '.' ]) : mixed
  • If the key is '*', clears the whole array.
  • Supports string path ("a.b.c") or array path (['a','b','c']).
  • If the path is partially invalid, the array is returned unchanged.
Parameters
$target : mixed

The array to modify (ignored if not an array).

$key : string|array<string|int, mixed>

The key path to delete.

$separator : string = '.'

The separator for string key paths (default: '.').

Tags
example
$data =
[
    'user' =>
    [
        'profile' =>
        [
            'name' => 'Alice',
            'age' => 30
        ],
        'active' => true
    ]
];

// Remove a nested key
$result = delete($data, 'user.profile.age');
print_r($result);
// [
//     'user' => [
//         'profile' => ['name' => 'Alice'],
//         'active'  => true
//     ]
// ]

// Remove a top-level key
$result = delete($data, 'user.active');

// Remove all keys
$result = delete($data, '*');
print_r($result); // []

// Using array path
$result = delete($data, ['user', 'profile', 'name']);
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

The modified array (or original if not an array).

ensureArrayPath()

Ensures that a given key in an array contains a sub-array, and returns it by reference.

& ensureArrayPath(array<string|int, mixed> &$current, string $segment) : array<string|int, mixed>

If the key does not exist or is not an array, it initializes it as an empty array. This is useful for building nested structures dynamically using references.

Parameters
$current : array<string|int, mixed>

The parent array passed by reference.

$segment : string

The key to check or initialize as an array.

Tags
example
$data = [];
$sub =& ensureArrayPath($data, 'user');
$sub['name'] = 'Alice';
// $data now becomes: ['user' => ['name' => 'Alice']]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

A reference to the array stored at the specified key.

exists()

Checks whether a key exists in an array or an object implementing ArrayAccess.

exists(array<string|int, mixed>|ArrayAccess $array, string|int|null $key[, string $separator = '.' ]) : bool
  • Returns false if the key is null or an empty string.
  • Supports both native arrays and ArrayAccess objects.
Parameters
$array : array<string|int, mixed>|ArrayAccess

The array or object to inspect.

$key : string|int|null

The key to check for existence.

$separator : string = '.'

The separator used in the key path. Default is '.'.

Tags
example
use oihana\core\arrays\exists;

// Flat array
$data = ['name' => 'Alice'];
var_dump(exists($data, 'name')); // true
var_dump(exists($data, 'age'));  // false

// Nested array
$data = ['user' => ['address' => ['country' => 'France']]];
var_dump(exists($data, 'user.address.country')); // true
var_dump(exists($data, 'user.address.city'));    // false

// Mixed with numeric keys
$data = ['items' => [0 => ['id' => 1], 1 => ['id' => 2]]];
var_dump(exists($data, 'items.1.id')); // true

// With null or empty key
var_dump(exists($data, null)); // false
var_dump(exists($data, ''));   // false
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

True if the key exists, false otherwise.

flatten()

Flattens a nested array into a single-level array.

flatten(array<string|int, mixed> $array) : array<string|int, mixed>

This function recursively iterates through the nested arrays, concatenating all nested values into one flat array.

Parameters
$array : array<string|int, mixed>

The array to flatten.

Tags
example
$nested = [1, [2, 3], [[4], 5], 6];
$flat = flatten($nested);
// Result: [1, 2, 3, 4, 5, 6]

$complex = ['a', ['b', ['c', 'd']], 'e'];
$flat = flatten($complex);
// Result: ['a', 'b', 'c', 'd', 'e']
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The flattened array, containing all nested values in order.

get()

Retrieves a value from an associative array using a key path.

get(array<string|int, mixed> $array, string|null $key[, mixed $default = null ][, string $separator = '.' ]) : mixed

This function allows navigation through a nested array using a key composed of segments separated by a specified separator (default is a dot). If the key is not found, the function returns a default value.

Parameters
$array : array<string|int, mixed>

The associative array to search within.

$key : string|null

The key path as a string. Can be null, in which case the function returns the entire array.

$default : mixed = null

The default value to return if the key is not found. Defaults to null.

$separator : string = '.'

The separator used to split the key into segments. Defaults to a dot ('.').

Tags
example
$data =
[
    'user' =>
    [
        'name'    => 'Alice',
        'address' =>
        [
            'city' => 'Paris',
            'geo' => [ 'lat' => 48.8566, 'lng' => 2.3522 ],
        ],
    ],
];

echo get($data, 'user.name');             // Alice
echo get($data, 'user.address.city');     // Paris
echo get($data, 'user.address.geo.lat');  // 48.8566
echo get($data, 'user.phone', 'unknown'); // unknown
echo get($data, null);                    // returns entire $data array
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
mixed

The value found in the array or the default value if the key does not exist.

getFirstKey()

Returns the first key from the provided list of keys that exists in the given array.

getFirstKey(array<string|int, mixed> $array, array<string|int, mixed> $keys[, mixed $default = null ]) : mixed

If none of the keys exist, the default value is returned.

Parameters
$array : array<string|int, mixed>

The array to search within.

$keys : array<string|int, mixed>

An ordered list of keys to check in the array.

$default : mixed = null

The value to return if none of the keys exist in the array. Default is null.

Tags
example
use function oihana\core\arrays\getFirstKey;

$definition =
[
    'list'   => [ 1 , 2 , 3 ] ,
    'concat' => 'abc' ,
];

$key = getFirstKey($definition, ['array', 'list', 'concat'], 'concat');
// $key === 'list'
author

Marc Alcaraz

since
1.0.0
Return values
mixed

Returns the first matching key if found, otherwise returns the default value.

getFirstValue()

Returns the value of the first key from the provided list of keys that exists in the given array.

getFirstValue(array<string|int, mixed> $array, array<string|int, mixed> $keys[, mixed $default = null ]) : mixed

If none of the keys exist, the default value is returned.

Parameters
$array : array<string|int, mixed>

The array to search within.

$keys : array<string|int, mixed>

An ordered list of keys to check in the array.

$default : mixed = null

The value to return if none of the keys exist in the array. Default is null.

Tags
example
use function oihana\core\arrays\getFirstValue;

$definition = [
    'list' => [1, 2, 3],
    'concat' => 'abc',
];

$value = getFirstValue($definition, ['array', 'list', 'concat'], 'default');
// $value === [1, 2, 3]
author

Marc Alcaraz

since
1.0.0
Return values
mixed

Returns the value corresponding to the first matching key if found, otherwise returns the default value.

hasIntKeys()

Indicates if all the keys in an array are integers.

hasIntKeys(array<string|int, mixed> $array) : bool

This function checks if every key in the provided array is an integer. Returns true only if all keys are integers, false otherwise.

Parameters
$array : array<string|int, mixed>

The array to check.

Tags
example
$arr1 = [10 => 'a', 20 => 'b', 30 => 'c'];
var_dump(hasIntKeys($arr1)); // true

$arr2 = ['0' => 'a', 1 => 'b', 2 => 'c'];
var_dump(hasIntKeys($arr2)); // false, because '0' is string key, not int

$arr3 = ['foo' => 'bar', 42 => 'baz'];
var_dump(hasIntKeys($arr3)); // false

$arr4 = [];
var_dump(hasIntKeys($arr4)); // true (no keys, so vacuously true)
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

True if all keys are integers, false otherwise.

hasStringKeys()

Indicates if all the keys in an array are strings.

hasStringKeys(array<string|int, mixed> $array) : bool

This function checks if every key in the provided array is a string. Returns true only if all keys are strings, false otherwise.

Parameters
$array : array<string|int, mixed>

The array to check.

Tags
example
$arr1 = ['foo' => 1, 'bar' => 2, 'baz' => 3];
var_dump(hasStringKeys($arr1)); // true

$arr2 = ['0' => 'a', '1' => 'b', '2' => 'c'];
var_dump(hasStringKeys($arr2)); // true, keys are strings '0', '1', '2'

$arr3 = [0 => 'zero', 1 => 'one', 2 => 'two'];
var_dump(hasStringKeys($arr3)); // false, keys are integers

$arr4 = ['foo' => 'bar', 42 => 'baz'];
var_dump(hasStringKeys($arr4)); // false, mixed keys (string and int)

$arr5 = [];
var_dump(hasStringKeys($arr5)); // true (empty array, vacuously true)
Return values
bool

True if all keys are strings, false otherwise.

inBetween()

Insert an element between all the items in an array.

inBetween(array<string|int, mixed> $source, mixed $element) : array<string|int, mixed>
Parameters
$source : array<string|int, mixed>

The source array

$element : mixed

The element to insert between items

Tags
example
print_r( inBetween(['a', 'b', 'c'], '/') ) ; // ["a", "/", "b", "/", "c"]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

A new array with elements inserted between original items

isAssociative()

Determines if an array is associative.

isAssociative(array<string|int, mixed> $array) : bool

Usage :

```php
use function core\arrays\isAssociative ;
$array =
[
  'id'          => 1 ,
  'created'     => null ,
  'name'        => 'hello world' ,
  'description' => null
];
echo json_encode( isAssociative( $array ) ) ;
```
Parameters
$array : array<string|int, mixed>

The array to evaluate.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

Indicates if the array is associative.

isIndexed()

Determines if an array is indexed (i.e., has sequential integer keys starting at 0).

isIndexed(array<string|int, mixed> $array) : bool

An array is considered indexed if its keys are exactly the sequence 0, 1, 2, ... n-1, where n is the number of elements in the array. This is typical for arrays used as lists.

Empty arrays are considered indexed by definition.

Parameters
$array : array<string|int, mixed>

The array to evaluate.

Tags
example
use function core\arrays\isIndexed ;

$array = [ 'a', 'b' , 'c' ] ;
echo json_encode( isIndexed( $array ) ) ;
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
bool

True if the array is indexed, false otherwise.

removeKeys()

Removes a set of keys from an array.

removeKeys(array<string|int, mixed> $array[, array<string|int, mixed> $keys = [] ][, bool $clone = false ]) : array<string|int, mixed>

This function removes the specified keys from the given array. If $clone is set to true, the original array is not modified; instead, a new array is returned. Otherwise, the original array is modified directly (passed by value).

Parameters
$array : array<string|int, mixed>

The input array to modify or clone.

$keys : array<string|int, mixed> = []

An array of keys to remove from the input array.

$clone : bool = false

If true, operates on a copy of the array and returns it; otherwise, modifies the array in place (by value).

Tags
example
use function oihana\core\arrays\removeKeys;

$input = ['name' => 'Alice', 'email' => 'alice@example.com', 'age' => 30];

// Example 1: Remove one key (in-place behavior)
$result = removeKeys($input, ['email']);
// $result = ['name' => 'Alice', 'age' => 30]

// Example 2: Remove multiple keys
$result = removeKeys($input, ['name', 'age']);
// $result = ['email' => 'alice@example.com']

// Example 3: Use clone to preserve the original array
$original = ['a' => 1, 'b' => 2, 'c' => 3];
$copy = removeKeys($original, ['a'], true);
// $original remains unchanged: ['a' => 1, 'b' => 2, 'c' => 3]
// $copy = ['b' => 2, 'c' => 3]

// Example 4: Key not found (no error)
$result = removeKeys(['x' => 1], ['y']);
// $result = ['x' => 1]

// Example 5: Empty key list
$result = removeKeys(['foo' => 'bar'], []);
// $result = ['foo' => 'bar']
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The resulting array with specified keys removed.

set()

Sets a value in an associative array using a key path.

set(array<string|int, mixed> &$array, string|null $key, mixed $value[, string $separator = '.' ][, bool $copy = false ]) : array<string|int, mixed>

If no key is given to the method, the entire array will be replaced.

Parameters
$array : array<string|int, mixed>

The associative array to modify (by reference).

$key : string|null

The key path as a string. Can be null, in which case the function replaces the entire array.

$value : mixed

The value to set.

$separator : string = '.'

The separator used to split the key into segments. Defaults to a dot ('.').

$copy : bool = false

If true, returns a modified copy instead of altering the original array.

Tags
example
$data = [];
set( $data , 'user.name' , 'Alice' ) ;
// $data => ['user' => ['name' => 'Alice']]

set( $data , null, ['id' => 1] ) ;
// $data => ['id' => 1]

$data = ['user' => ['name' => 'Marc']];
$new = set($data, 'user.address.country', 'France', '.', true);
print_r( $new ); // ['user' => ['name' => 'Marc', 'address' => ['country' => 'France']]]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The updated ( or copied and modified ) array.

setArrayValue()

Sets a value in a flat associative array using a single key.

setArrayValue(array<string|int, mixed> $document, string $key, mixed $value) : array<string|int, mixed>

This helper function assigns the given value to the specified key in the provided array. It does not support nested keys or separators.

The array is returned with the updated value, leaving the original array unmodified if passed by value.

Parameters
$document : array<string|int, mixed>

The associative array to modify.

$key : string

The key at which to set the value.

$value : mixed

The value to assign to the key.

Tags
example
$data = ['name' => 'Alice'];
$updated = setArrayValue($data, 'age', 30);
// $updated = ['name' => 'Alice', 'age' => 30];
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The modified array with the new or updated key/value pair.

shuffle()

Shuffles the elements of an array in place using the Fisher-Yates algorithm.

shuffle(array<string|int, mixed> &$ar) : array<string|int, mixed>

This function randomizes the order of the elements in the given array. It operates directly on the passed array (by reference) and also returns it. The algorithm used ensures an unbiased shuffle.

If the array has 0 or 1 element, it is returned as is without changes.

Parameters
$ar : array<string|int, mixed>

The array to shuffle (passed by reference).

Tags
example
use function oihana\core\arrays\shuffle;

$numbers = [1, 2, 3, 4, 5];
shuffle($numbers);
print_r($numbers); // e.g. [3, 1, 5, 2, 4] - order randomized

$empty = [];
shuffle($empty);
var_dump($empty); // []

$single = [42];
shuffle($single);
var_dump($single); // [42]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The shuffled array.

stub()

Returns a new empty array.

stub() : array<string|int, mixed>

This function is useful as a placeholder or default value generator when an empty array is needed.

Tags
example
use function oihana\core\arrays\stub;

$emptyArray = stub();
var_dump($emptyArray); // outputs: array(0) }
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

An empty array.

swap()

Swaps two indexed values in a specific array representation.

swap(array<string|int, mixed> $ar[, int|string $from = 0 ][, int|string $to = 0 ][, bool $copy = false ]) : array<string|int, mixed>

Supports both integer and string keys. Negative indices are supported to count from the end (e.g. -1 is the last element).

If $copy is true, returns a new array with swapped values, leaving original intact. Otherwise, swaps values directly on the passed array.

Parameters
$ar : array<string|int, mixed>

The array of values to change

$from : int|string = 0

The first key/index position to swap (default: 0)

$to : int|string = 0

The second key/index position to swap (default: 0)

$copy : bool = false

If true, returns a swapped clone of the passed-in array (default: false)

Tags
example
$ar = [1, 2, 3, 4];
swap($ar, 1, 3);
print_r($ar); // [1, 4, 3, 2]

$arAssoc = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$swapped = swap($arAssoc, 'a', 'c', true);
print_r($swapped); // ['c' => 'cherry', 'b' => 'banana', 'a' => 'apple']
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The modified array reference.

tail()

Returns a new array containing all elements except the first one.

tail(array<string|int, mixed> $array) : array<string|int, mixed>

If the input array is empty, returns an empty array.

Parameters
$array : array<string|int, mixed>

The input array.

Tags
example
use function oihana\core\arrays\tail;

$arr = [2, 3, 4];
print_r(tail($arr)); // Outputs: [3, 4]

$empty = [];
print_r(tail($empty)); // Outputs: []

$single = [10];
print_r(tail($single)); // Outputs: []
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

A new array without the first element.

toArray()

Ensures the given value is returned as an array.

toArray(mixed $value) : array<string|int, mixed>

If the value is already an array, it is returned unchanged. Otherwise, the value is wrapped inside a new array.

Parameters
$value : mixed

The value to encapsulate in an array.

Tags
example
use function oihana\core\arrays\toArray;

$a = toArray(123);
print_r($a); // [123]

$b = toArray("hello");
print_r($b); // ["hello"]

$c = toArray([1, 2, 3]);
print_r($c); // [1, 2, 3]

$d = toArray(null);
print_r($d); // [null]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The value wrapped in an array, or the original array if already an array.

unique()

Removes duplicate values from an array and reindexes it.

unique(array<string|int, mixed> $array[, int $flags = SORT_STRING ]) : array<string|int, mixed>

Combines the functionality of array_unique() and array_values(): first removes duplicates, then reindexes the array numerically starting at 0.

The optional $flags parameter modifies the comparison behavior, possible values:

  • SORT_REGULAR: Compare items normally (don't change types).
  • SORT_NUMERIC: Compare items numerically.
  • SORT_STRING: Compare items as strings.
  • SORT_LOCALE_STRING: Compare items as strings, based on the current locale.
Parameters
$array : array<string|int, mixed>

The input array.

$flags : int = SORT_STRING

[optional] Comparison behavior flag. Default is SORT_STRING.

Tags
example
use function oihana\core\arrays\unique;

$array = ['a', 'b', 'a', 'c', 'b'];
$result = unique($array);
print_r($result); // ['a', 'b', 'c']

$numericArray = [1, 2, '1', 3];
$resultNumeric = unique($numericArray, SORT_NUMERIC);
print_r($resultNumeric); // [1, 2, 3]
link
https://www.php.net/manual/en/function.array-unique.php
link
https://www.php.net/manual/en/function.array-values.php
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The filtered array with unique values, reindexed from 0.


        
On this page

Search results