Skip to content

📦 Arr Class

A utility class for working with arrays. Supports dot-notation access, structure checks, deep JSON decoding, key filtering, and key-based array merging.

🔑 get(array $array, string $key, $default = null)

Retrieves a value from an array using dot notation.

📌 Example:

php
$data = ['user' => ['name' => 'Alice']];
$name = Arr::get($data, 'user.name'); // 'Alice'

📝 set(array &$array, string $key, $value): void

Sets a value in an array using dot notation.

📌 Example:

php
$data = [];
Arr::set($data, 'user.email', 'test@example.com');
// $data = ['user' => ['email' => 'test@example.com']]

📋 isList(array $array): bool

Checks if the array is a list (sequential numeric keys starting from 0).

📌 Example:

php
Arr::isList(['a', 'b']); // true
Arr::isList(['a' => 1, 'b' => 2]); // false

📁 isAssoc(array $array): bool

Checks if the array is associative (non-sequential or string keys).

📌 Example:

php
Arr::isAssoc(['a' => 1, 'b' => 2]); // true

🌲 depth(array $array): int

Returns the maximum depth of nested arrays.

📌 Example:

php
Arr::depth([1, [2, [3]]]); // 3

🧠 jsonDecode($data, $assoc = true, $depth = 512, $options = 0)

Recursively decodes JSON strings, even if they are nested in arrays.

📌 Example:

php
$json = '{"user":"{\"name\":\"Alice\"}"}';
$result = Arr::jsonDecode($json);
// ['user' => ['name' => 'Alice']]

🚫 exceptKeys(array $array, array $keys): array

Removes the given keys from the array.

📌 Example:

php
$data = ['name' => 'Alice', 'email' => 'a@example.com'];
$result = Arr::exceptKeys($data, ['email']);
// ['name' => 'Alice']

onlyKeys(array $array, array $keys): array

Keeps only the specified keys in the array.

📌 Example:

php
$data = ['name' => 'Alice', 'email' => 'a@example.com'];
$result = Arr::onlyKeys($data, ['email']);
// ['email' => 'a@example.com']

🔗 mergeByKeyMatch(array $base, array $extra, string $key): array

Merges two arrays by matching the value of a specific key.

📌 Example:

php
$base = [['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']];
$extra = [['id' => 2, 'email' => 'bob@example.com']];
$result = Arr::mergeByKeyMatch($base, $extra, 'id');

/*
[
  ['id' => 1, 'name' => 'Alice'],
  ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com']
]
*/

© PageBlocks 2019-present