Arr Class

Table of contents

  1. Overview
  2. Basic Usage
  3. Methods
  4. Retrieving Data
  5. Iteration, Sorting, Ordering, & Transformation
  6. Manipulation
  7. Comparison, Checking, Filtering, & Mapping
  8. Chunking and Collapsing
  9. Mapping and Recursive Operations
  10. Other Utilities

1. Overview Table of Contents

A collection of functions for manipulating arrays that are chainable. To use this class make sure it is properly loaded:

use Core\Lib\Utilities\ArraySet;


2. Basic Usage Table of Contents

To use the ArraySet class, instantiate it with an array:

$arr = new ArraySet([1, 2, 3, 4]);



Initializing when you don’t know if the variable is an instance of the Arr class or an array type.

$errors = $errors instanceof Arr ? $errors : new ArraySet($errors);



Most methods support chaining:

$arr = (new ArraySet([5, 3, 8, 1]))
    ->sort()
    ->reverse()
    ->all(); 

print_r($arr); // Output: [8, 5, 3, 1]



Examples

$data = new ArraySet(['name' => 'John', 'age' => 30]);

// Get a value
echo $data->get('name'); // John

// Sort values
$sorted = (new ArraySet([3, 1, 2]))->sort()->all(); // [1, 2, 3]

// Filter
$filtered = (new ArraySet([1, 2, 3, 4]))->where(fn($n) => $n > 2)->all(); // [3, 4]

$data = new ArraySet([
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
]);

// Get only the names
$names = $data->column('name')->all(); 
// ['Alice', 'Bob']

// Remove a key
$filtered = (new ArraySet(['name' => 'John', 'age' => 30]))->except('age')->all();
// ['name' => 'John']

// Check for a value
$hasTwo = (new ArraySet([1, 2, 3, 4]))->contains(2)->result(); 
// true

$arr = new ArraySet([
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 25]
]);

$arr->multiSort(SORT_ASC)->all();
/*
[
    ['name' => 'Bob', 'age' => 25],
    ['name' => 'Alice', 'age' => 30]
]
*/


3. Methods Table of Contents

A. Constructor

__construct(array $items = [])

Initializes an Arr instance.

$arr = new ArraySet(['name' => 'John', 'age' => 30]);


B. make

make(mixed $items = [])

Wraps a value into an array if it’s not already an array.

$arr = Arr::make('Hello')->all(); // Output: ['Hello']


4. Retrieving Data Table of Contents

A. all

‘all(): array’

Returns the array.

$arr = new ArraySet([1, 2, 3]);
print_r($arr->all()); // [1, 2, 3]


B. column

column(string|int $columnKey): self

Extracts values from a specific column in a multi-dimensional array.

$arr = new ArraySet([
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob']
]);
$arr->column('name')->all();
// ['Alice', 'Bob']


C. count

count(): self

Returns the number of elements in the array.

$arr = new ArraySet([1, 2, 3, 4]);
echo $arr->count()->result(); 
// 4


D. exists

exists(string $key): self

Checks if a given key exists in the array.

$arr = new ArraySet(['name' => 'John', 'age' => 30]);
var_dump($arr->exists('age')->result());
// true


E. first

first(?callable $callback = null): self

Retrieves the first element of the array, or the first element that matches a given condition.

$arr = new ArraySet([10, 20, 30, 40]);
echo $arr->first()->result(); 
// 10

// With a condition
$arr = new ArraySet([10, 20, 30, 40]);
echo $arr->first(fn($v) => $v > 25)->result(); 
// 30


F. firstKey

firstKey(): self

Retrieves the first key of the array.

$arr = new ArraySet(['name' => 'Alice', 'age' => 30]);
echo $arr->firstKey()->result();
// name


G. get

get(string $key, mixed $default = null)

Retrieves a value by key, supporting dot notation.

$data = new ArraySet(['user' => ['name' => 'John']]);
echo $data->get('user.name'); // John


H. has

has(string $key)

Checks if a key exists.

$arr = new ArraySet(['name' => 'John']);
var_dump($arr->has('name')); // true


I. hasAny

hasAny(array|string $keys)

Checks if at least one key exists.

$arr = new ArraySet(['name' => 'John', 'age' => 30]);
var_dump($arr->hasAny(['name', 'email'])); // true


J. keys

keys()

Returns the array keys.

$arr = new ArraySet(['a' => 1, 'b' => 2]);
print_r($arr->keys()->all()); // ['a', 'b']


K. last

last(?callable $callback = null): self

Retrieves the last element of the array, or the last element that matches a given condition.

$arr = new ArraySet([10, 20, 30, 40]);
echo $arr->last()->result(); 
// 40

// With a condition
$arr = new ArraySet([10, 20, 30, 40]);
echo $arr->last(fn($v) => $v < 25)->result(); 
// 20


L. lastKey

lastKey(): self

Retrieves the last key of the array.

$arr = new ArraySet(['name' => 'Alice', 'age' => 30]);
echo $arr->lastKey()->result();
// age


M. result

result(): mixed

Retrieves the last computed result from a function that does not modify the original array.

$arr = new ArraySet([1, 2, 3]);
$arr->count();
print_r($arr->result());
// 3


N. search

search(mixed $value): self

Searches for a value in the array and returns its key.

$arr = new ArraySet(['apple' => 'red', 'banana' => 'yellow']);
$arr->search('yellow');
print_r($arr->result());
// 'banana'


O. shift

shift(): self

Removes and returns the first item from the array.

$arr = new ArraySet([1, 2, 3, 4]);
$arr->shift();
print_r($arr->all());
print_r($arr->result());
// [2, 3, 4]
// 1


P. values

values()

Returns only the array values.

$arr = new ArraySet(['a' => 1, 'b' => 2]);
print_r($arr->values()->all()); // [1, 2]


5. Iteration, Sorting, Ordering, & Transformation Table of Contents

A. asort

asort()

Sorts while maintaining key association.

$arr = new ArraySet(['b' => 3, 'a' => 1, 'c' => 2]);
$arr->asort()->all(); // ['a' => 1, 'c' => 2, 'b' => 3]


B. arsort

arsort()

Sorts in descending order while maintaining key association.

$arr = new ArraySet(['b' => 3, 'a' => 1, 'c' => 2]);
$arr->arsort()->all(); // ['b' => 3, 'c' => 2, 'a' => 1]


C. flatten

flatten(): self

Flattens a multi-dimensional array into a single-level array.

$arr = new ArraySet([[1, 2], [3, 4], [5]]);
$arr->flatten()->all();
// [1, 2, 3, 4, 5]


D. flip

flip(): self

Swaps the keys and values of an array.

$arr = new ArraySet(['name' => 'Alice', 'age' => 30]);
$arr->flip()->all();
// ['Alice' => 'name', '30' => 'age']


E. keyBy

keyBy(string $key): self

Uses a specific field in a multi-dimensional array as the key.

$arr = new ArraySet([
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob']
]);
$arr->keyBy('id')->all();
/*
[
    1 => ['id' => 1, 'name' => 'Alice'],
    2 => ['id' => 2, 'name' => 'Bob']
]
*/


F. krsort

krsort(): self

Sorts an array by keys in descending order.

$arr = new ArraySet(['b' => 2, 'a' => 1, 'c' => 3]);
$arr->krsort()->all();
// ['c' => 3, 'b' => 2, 'a' => 1]


G. ksort

ksort(): self

Sorts an array by keys in ascending order.

$arr = new ArraySet(['b' => 2, 'a' => 1, 'c' => 3]);
$arr->ksort()->all();
// ['a' => 1, 'b' => 2, 'c' => 3]


H. sort

sort(int $sortFlags = SORT_REGULAR)

Sorts values in ascending order.

$arr = new ArraySet([5, 3, 8, 1]);
$arr->sort()->all(); // [1, 3, 5, 8]


I. rsort

rsort() Sorts in descending order.

$arr = new ArraySet([5, 3, 8, 1]);
$arr->rsort()->all(); // [8, 5, 3, 1]


J. usort

usort(callable $callback): self

Sorts the array using a user-defined comparison function.

$arr = new ArraySet([3, 1, 4, 2]);
$arr->usort(fn($a, $b) => $a <=> $b);
print_r($arr->all());
// [1, 2, 3, 4]


K. walk

walk(callable $callback): self

Applies a user function to every item in the array.

$arr = new ArraySet([1, 2, 3]);
$arr->walk(fn(&$value) => $value *= 2);
print_r($arr->all());
// [2, 4, 6]


L. walkRecursive

walkRecursive(callable $callback): self

Applies a user function to every item in a multi-dimensional array.

$arr = new ArraySet([
    ['value' => 1],
    ['value' => 2]
]);
$arr->walkRecursive(fn(&$value) => is_numeric($value) ? $value *= 2 : $value);
print_r($arr->all());
//  [['value' => 2], ['value' => 4]]


M. Manipulation Table of Contents

A. add

add(string $key, mixed $value)

Adds a value if the key does not exist.

$arr = new ArraySet(['name' => 'John']);
$arr->add('age', 30)->all(); // ['name' => 'John', 'age' => 30]


B. clear

clear()

Removes all elements.

$arr = new ArraySet([1, 2, 3]);
$arr->clear()->all(); // []


C. combine

combine(array $keys, array $values): self

Combines two arrays, one as keys and one as values.

$keys = ['name', 'age', 'city'];
$values = ['John', 30, 'New York'];

$arr = Arr::combine($keys, $values);
$arr->all();
// ['name' => 'John', 'age' => 30, 'city' => 'New York']


D. crossJoin

crossJoin(array ...$arrays): self

Computes the Cartesian product of multiple arrays.

$arr = new ArraySet([1, 2]);
$arr->crossJoin(['A', 'B'])->all();
/*
[
    [1, 'A'], [1, 'B'],
    [2, 'A'], [2, 'B']
]
*/


E. dot

dot(string $prepend = ''): self

Converts a multi-dimensional array into a dot notation format.

$arr = new ArraySet([
    'user' => ['name' => 'John', 'age' => 30]
]);
$arr->dot()->all();
// ['user.name' => 'John', 'user.age' => 30]


F. each

each(callable $callback): self

Applies a callback to each element in the array.

$arr = new ArraySet([1, 2, 3]);
$arr->each(function ($value, $key) {
    echo "$key => $value\n";
});
/*
0 => 1
1 => 2
2 => 3
*/


G. except

except(array|string $keys): self

Removes specific keys from the array.

$arr = new ArraySet(['name' => 'John', 'age' => 30, 'city' => 'New York']);
$arr->except('age')->all();
// ['name' => 'John', 'city' => 'New York']


H. fill

fill(int $start, int $count, mixed $value): self

Fills the array with a specified value starting at a given index and continuing for a specified number of elements.

$arr = new ArraySet([1, 2, 3]);
$arr->fill(1, 3, "X");

print_r($arr->all());
//[1, "X", "X", "X"]


I. forget

forget(string $key)

Removes an item by key.

$arr = new ArraySet(['name' => 'John', 'age' => 30]);
$arr->forget('name')->all(); // ['age' => 30]


J. merge

merge(array $array)

Merges another array.

$arr = new ArraySet(['name' => 'John']);
$arr->merge(['age' => 30])->all(); // ['name' => 'John', 'age' => 30]


K. only

only(array|string $keys): self

Returns a new array containing only the specified keys.

$arr = new ArraySet(['name' => 'John', 'age' => 30, 'city' => 'New York']);
$arr->only(['name', 'city']);
print_r($arr->all());
// ['name' => 'John', 'city' => 'New York']


L. pad

pad(int $size, mixed $value): self

Expands the array to a specified size by padding it with a given value.

$arr = new ArraySet([1, 2, 3]);
$arr->pad(5, 0);
print_r($arr->all());
// [1, 2, 3, 0, 0]


M. pluck

pluck(string $key): self

Extracts values from an array of associative arrays based on a given key.

$arr = new ArraySet([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25]
]);
$arr->pluck('name');
print_r($arr->all());
// ['John', 'Jane']


N. prepend

prepend(mixed $value): self

Adds a value to the beginning of the array.

$arr = new ArraySet([2, 3, 4]);
$arr->prepend(1);
print_r($arr->all());
// [1, 2, 3, 4]


O. pull

pull(string $key, mixed $default = null): self

Retrieves a value from the array and removes it.

$arr = new ArraySet(['name' => 'John', 'age' => 30]);
$arr->pull('age');
print_r($arr->all());
print_r($arr->result());
// ['name' => 'John']
// 30


P. push

push(mixed ...$values): self

Adds one or more values to the end of the array.

$arr = new ArraySet([1, 2, 3]);
$arr->push(4, 5);
print_r($arr->all());
// [1, 2, 3, 4, 5]


Q. reduce

reduce(callable $callback, mixed $initial = null): self

Reduces the array to a single value using a callback function.

$arr = new ArraySet([1, 2, 3, 4]);
$arr->reduce(fn($carry, $item) => $carry + $item, 0);
print_r($arr->result());
// 10


R. replace

replace(array $array): self

Replaces values in the current array with values from another array.

$arr = new ArraySet(['name' => 'John', 'age' => 30]);
$arr->replace(['age' => 35, 'city' => 'New York']);
print_r($arr->all());
// ['name' => 'John', 'age' => 35, 'city' => 'New York']


S. set

set(string $key, mixed $value)

Sets a value using dot notation.

$arr = new ArraySet([]);
$arr->set('user.name', 'John')->all(); // ['user' => ['name' => 'John']]


T. shuffle

shuffle(): self

Randomly shuffles the elements in the array.

$arr = new ArraySet([1, 2, 3, 4, 5]);
$arr->shuffle();
print_r($arr->all());

// Output may vary
// [3, 5, 1, 4, 2] 


U. shuffleAssociative

shuffleAssociative(): self

Shuffles the elements of an associative array while preserving key-value relationships.

$arr = new ArraySet(['a' => 1, 'b' => 2, 'c' => 3]);
$arr->shuffleAssociative();
print_r($arr->all());

// Output may vary
// ['c' => 3, 'a' => 1, 'b' => 2]


V. slice

slice(int $offset, ?int $length = null): self

Extracts a portion of the array.

$arr = new ArraySet([1, 2, 3, 4, 5]);
$arr->slice(1, 3);
print_r($arr->all());
// [2, 3, 4]


W. splice

splice(int $offset, ?int $length = null, array $replacement = []): self

Removes and replaces a portion of the array.

$arr = new ArraySet([1, 2, 3, 4, 5]);
$arr->splice(2, 2, [6, 7]);
print_r($arr->all());
// [1, 2, 6, 7, 5]


X. udiff

udiff(array $array, callable $callback): self

Computes the difference between arrays using a custom comparison function.

$arr1 = new ArraySet([1, 2, 3, 4, 5]);
$arr2 = [3, 4];

$arr1->udiff($arr2, fn($a, $b) => $a <=> $b);
print_r($arr1->all());
// [1, 2, 5]


7. Comparison, Checking, Filtering, & Mapping Table of Contents

A. contains

contains(mixed $value, bool $strict = false): self

Checks if an array contains a specific value.

$arr = new ArraySet([1, 2, 3, 4]);
var_dump($arr->contains(3)->result());
// true


B. diff

diff(array $array): self

Finds the difference between the current array and another array.

$arr = new ArraySet([1, 2, 3, 4]);
$arr->diff([2, 4])->all();
// [1, 3]


C. filter

filter(callable $callback)

Filters elements based on a condition.

$arr = new ArraySet([1, 2, 3, 4]);
$arr->filter(fn($n) => $n % 2 === 0)->all(); // [2, 4]


D. intersect

intersect(array $array): self

Finds the common values between the current array and another array.

$arr = new ArraySet([1, 2, 3, 4]);
$arr->intersect([2, 4, 6])->all();
// [2, 4]


E. intersectKeys

intersectKeys(array $array): self

Finds elements whose keys exist in another array.

$arr = new ArraySet(['name' => 'Alice', 'age' => 30, 'city' => 'New York']);
$arr->intersectKeys(['age' => '', 'city' => ''])->all();
// ['age' => 30, 'city' => 'New York']


F. isArray

isArray(mixed $value): self

Checks if the given value is an array.

$arr = new ArraySet();
var_dump($arr->isArray([1, 2, 3])->result()); 
// true


G. isEmpty

isEmpty(): self

Checks if the array is empty.

$arr = new ArraySet([]);
var_dump($arr->isEmpty()->result());
// true


H. map

map(callable $callback)

Applies a function to each item.

$arr = new ArraySet([1, 2, 3]);
$arr->map(fn($n) => $n * 2)->all(); // [2, 4, 6]


I. unique

unique()

Removes duplicate values.

$arr = new ArraySet([1, 2, 2, 3, 3]);
$arr->unique()->all(); // [1, 2, 3]


J. where

where(callable $callback)

Filters values where callback returns true.

$arr = new ArraySet([['age' => 18], ['age' => 25], ['age' => 30]]);
$arr->where(fn($item) => $item['age'] >= 25)->all(); 
// [['age' => 25], ['age' => 30]]


7. Chunking & Collapsing Table of Contents

A. chunk

chunk(int $size): self

Splits an array into chunks of the specified size.

$arr = new ArraySet([1, 2, 3, 4, 5, 6]);
$arr->chunk(2)->all(); 
// [[1, 2], [3, 4], [5, 6]]


B. collapse

collapse(): self

Flattens a multi-dimensional array into a single-level array.

$arr = new ArraySet([[1, 2], [3, 4], [5]]);
$arr->collapse()->all();
// [1, 2, 3, 4, 5]


7. Mapping and Recursive Operations Table of Contents

A. mapRecursive

mapRecursive(callable $callback): self

Recursively applies a callback function to each element in the array.

$arr = new ArraySet([
    [1, 2, 3],
    [4, 5, [6, 7]]
]);

$arr->mapRecursive(fn($v) => $v * 2)->all();
/*
[
    [2, 4, 6],
    [8, 10, [12, 14]]
]
*/


B. mapWithKeys

mapWithKeys(callable $callback): self

Maps an array using a callback that defines both keys and values.

$arr = new ArraySet(['name' => 'Alice', 'age' => 30]);
$arr->mapWithKeys(fn($v, $k) => [$k . '_modified' => $v])->all();
/*
[
    'name_modified' => 'Alice',
    'age_modified' => 30
]
*/


C. multiSort

multiSort(int $sortFlags = SORT_REGULAR): self

Sorts multiple arrays or multi-dimensional arrays.

$arr = new ArraySet([
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 25]
]);

$arr->multiSort(SORT_ASC)->all();
/*
[
    ['name' => 'Bob', 'age' => 25],
    ['name' => 'Alice', 'age' => 30]
]
*/


8. Other Utilities Table of Contents

A. implode

implode(string $separator)

Joins array values into a string.

$arr = new ArraySet(['apple', 'banana', 'cherry']);
echo $arr->implode(', '); // "apple, banana, cherry"


B. random

random(?int $number = null)

Retrieves a random value or values.

$arr = new ArraySet([1, 2, 3, 4]);
echo $arr->random(); // Random value from the array


C. reverse

reverse()

Reverses the order.

$arr = new ArraySet([1, 2, 3]);
$arr->reverse()->all(); // [3, 2, 1]

D. wrap

wrap(mixed $value): self

Ensures the given value is an array. If it’s not, wraps it in an array.

$arr = new ArraySet();
$arr->wrap('hello');
print_r($arr->all());
// ['hello']