Skip to main content

Array Helper

The Array_Helper class contains several helper methods that make working with native PHP arrays a little easier. These methods are all statically accessible, and can be chained together using the Array Processor.

Process

Instantiates an Array Processor, which allows an array to have any method in Array_Helper used in a chain.

// Outputs "1, 3, bar, baz, foo"
echo Array_Helper::process(['foo', 'bar', 'baz', null, 1, 3])
->where_not_null()
->sort(fn ($a, $b) => $a <=> $b)
->set_separator(', ');

Where Not Null

Helper method to filter out values that are null

//Returns ['foo','bar','baz']
Array_Helper::where_not_null(['foo','bar','baz',null]);

Each

Calls the specified callback on each item in a foreach loop. If the array is associative, the key is retained. Functional methods like this are particularly useful because they can require type safety in your callbacks.

The example below converts an array of tag names keyed by their URL-friendly slug into hashtags.

//Returns ['outer-banks' => '#OuterBanks', 'north-carolina' => '#NorthCarolina', 'travel' => '#Travel']
$hashtags = Array_Helper::each([
'outer-banks' => 'Outer Banks',
'north-carolina' => 'North Carolina',
'travel' => 'Travel',
], fn(string $value, string $key) => '#' . String_Helper::pascal_case($value));

After

Fetches items after the specified array position.

use Underpin\Helpers\Array_Helper;

//['bar','baz']
Array_Helper::after(['foo','bar','baz'],1);

Before

The opposite of Array_Helper::after. Fetches items before the specified array position.

use Underpin\Helpers\Array_Helper;

//['foo']
Array_Helper::before(['foo','bar','baz'],1);

Dot

Fetches an item from an array using a dot notation. Throws an Item_Not_Found if the item provided could not be located in the array.

use Underpin\Helpers\Array_Helper;

try{
// baz
Array_Helper::dot(['foo' => ['bar' => 'baz']], 'foo.bar')
}catch(Item_Not_Found $e){
// Handle cases where the item was not found.
}

Remove

Removes an item from the array, and returns the transformed array.

// ['peanut butter' => 'JIF', 'jelly' => 'Smucker\'s']
Array_Helper::remove(['milk' => 'Goshen Dairy','peanut butter' => 'JIF', 'jelly' => 'Smucker\'s'], 'milk');

Wrap

Forces an item to be an array, even if it isn't an array.

// [123]
Array_Helper::wrap(123);

Hydrate

Creates an array of new instances given the arguments to pass into the instance constructor.


class Tag{

public function __construct(public readonly string $slug, public readonly string $name){

}
}

// [(Tag),(Tag),(Tag)
Array_Helper::hydrate([
['rv-life', 'RVLife'],
['travel','Travel'],
['wordpress','WordPress']
],Tag::class)

Flatten

Flatten arrays of arrays into a single array where the parent array is embedded as an item keyed by the $key.

/**
* [
* ['id' => 'group-1', 'key' => 'value', 'another' => 'value'],
* ['id' => 'group-1', 'key' => 'another-value', 'another' => 'value'],
* ['id' => 'group-2', 'key' => 'value', 'another' => 'value'],
* ['id' => 'group-2', 'key' => 'another-value', 'another' => 'value']
* ]
*/
Array_Helper::flatten([
'group-1' => [['key' => 'value', 'another' => 'value'], ['key' => 'another-value', 'another' => 'value']],
'group-2' => [['key' => 'value', 'another' => 'value'], ['key' => 'another-value', 'another' => 'value']],
], 'id')

To Indexed

Updates the array to contain a key equal to the array's key value.

/**
* [
* ['slug' => 'travel','name' => 'Travel'],
* ['slug' => 'rv-life','name' => 'RV Life'],
* ['slug' => 'wordpress','name' => 'WordPress']
* ]
*/
Array_Helper::to_indexed(['travel' => 'Travel','rv-life' => 'RVLife','wordpress' => 'Wordpress'], 'slug', 'name');

Sort

Sorts array using the specified subject, sorting method, and direction. Transforms the array directly.

$items = ['bar','foo','baz'];

// ['foo', 'baz', 'bar']
Array_Helper::sort($items,SORT_REGULAR,Direction::Descending);

This also supports providing a callback for the sort, instead:

class Tag{

public function __construct(public readonly string $slug, public readonly string $name){

}
}

$items = [
new Tag('rv-life','RV Life'),
new Tag('travel','Travel'),
new Tag('outer-banks', 'Outer Banks'),
new Tag('taos', 'Taos')
];

// [Tag(outer-banks), Tag(rv-life), Tag(taos), Tag(travel)]
Array_Helper::sort($items,fn(Tag $a, Tag $b) => $a->slug <=> $b->slug);

Pluck

Plucks a single item from an array, given a key. Falls back to a default value if it is not set.

// 'bar'
Array_Helper::pluck(['foo' => 'bar'],'foo','baz');

// 'baz'
Array_Helper::pluck(['foo' => 'bar'],'invalid','baz');

If the item is not an array, it will also provide the default value.

// 'baz'
Array_Helper::pluck('This is clearly not an array...and yet.','invalid','baz');

Pluck Recursive

Plucks a specific value from an array of items.

$items = [
['slug' => 'rv-life', 'name' => 'RVLife'],
['slug' => 'travel', 'name' => 'Travel'],
['slug' => 'wordpress', 'name' => 'WordPress'],
['name' => 'Invalid']
];

// ['rv-life','travel','outer-banks','taos', null]
Array_Helper::Pluck_Recursive($items,'slug', null);

This also works with objects:

class Tag{

public function __construct(public readonly string $slug, public readonly string $name){

}
}

$items = [
new Tag('rv-life','RV Life'),
new Tag('travel','Travel'),
new Tag('outer-banks', 'Outer Banks'),
new Tag('taos', 'Taos')
];

// ['rv-life','travel','outer-banks','taos']
Array_Helper::pluck_recursive($items, 'slug', null);

Cast

Cast all items in the array to the specified type.

// [1, 234,12,123,0,0]
Array_Helper::cast(['1','234','12.34',123,'alex',false], 'int');

Append

Adds the specified item(s) to the end of an array.

// ['foo','bar','baz']
Array_Helper::append(['foo'],'bar','baz');

Is Associative

Returns true if this array is an associative array.

// true
Array_Helper::is_associative(['foo' => 'bar']);

// false
Array_Helper::is_associative(['foo', 'bar', 'baz']);

Normalize

Recursively sorts, and optionally mutates an array of arrays. Useful when preparing for caching purposes because it ensures that any array that is technically identical, although in a different order, is the same. This can also convert a closure into a format that can be safely converted into a hash.

Generally, this is used to prepare an array to be converted into a consistent hash, regardless of what order the items in the array are stored.

$cached_query = [
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => [
'relation' => 'OR',
[
'key' => 'likes',
'value' => 50,
'compare' => '>',
'type' => 'numeric',
],
],
];

/**
* [
* 'meta_query' => [
* 'relation' => 'OR'
* [
* 'compare' => '>'
* 'key' => 'likes'
* 'type' => 'numeric'
* 'value' => 50
* ]
* ]
* 'post_type' => 'post'
* 'posts_per_page' => int -1
* ]
*/
Array_Helper::normalize($cached_query)

Proxies

There are also several methods that serve as direct proxies for array_* functions, with the only difference being that the order of the arguments always put the input array as the first argument (haystack comes first).

  • map => array_map
  • reduce => array_reduce
  • filter => array_filter
  • values => array_values
  • keys => array_keys
  • unique => array_unique
  • key_sort => ksort
  • merge => array_merge
  • reverse => array_reverse
  • prepend => array_unshift
  • intersect => array_intersect
  • intersect_keys => array_intersect_keys
  • diff => array_diff
  • replace_recursive => array_replace_recursive
  • replace => array_replace