Working with arrays in PHP or any other language can sometimes be difficult, especially when you need to filter, search, order and modify their contents. In this blog post, we’ll explore some of the key PHP methods and functions available in PHP under MIT License, for filtering, searching, ordering, and modifying arrays.

In this guide we’ll examine the following;

  • all
  • any
  • deepFlatten
  • drop
  • findLast
  • findLastIndex
  • flatten
  • groupBy
  • hasDuplicates
  • head
  • last
  • pluck
  • pull
  • reject
  • remove
  • tail
  • take
  • without
  • orderBy
  • bubbleSort
  • rotate

Array

all

Returns true if the provided function returns true for all elements of an array, false otherwise.

function all($items, $func)
{
    return count(array_filter($items, $func)) === count($items);
}
Examples
all([2, 3, 4, 5], function ($item) {
    return $item > 1;
}); // true

any

Returns true if the provided function returns true for at least one element of an array, false otherwise.

function any($items, $func)
{
    return count(array_filter($items, $func)) > 0;
}
Examples
any([1, 2, 3, 4], function ($item) {
    return $item < 2;
}); // true

deepFlatten

Deep flattens an array.

function deepFlatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            $result[] = $item;
        } else {
            $result = array_merge($result, deepFlatten($item));
        }
    }

    return $result;
}
Examples
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]

drop

Returns a new array with n elements removed from the left.

function drop($items, $n = 1)
{
    return array_slice($items, $n);
}
Examples
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]

findLast

Returns the last element for which the provided function returns a truthy value.

function findLast($items, $func)
{
    $filteredItems = array_filter($items, $func);

    return array_pop($filteredItems);
}
Examples
findLast([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});
// 3

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

function findLastIndex($items, $func)
{
    $keys = array_keys(array_filter($items, $func));

    return array_pop($keys);
}
Examples
findLastIndex([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});
// 2

flatten

Flattens an array up to the one level depth.

function flatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            $result[] = $item;
        } else {
            $result = array_merge($result, array_values($item));
        }
    }

    return $result;
}
Examples
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]

groupBy

Groups the elements of an array based on the given function.

function groupBy($items, $func)
{
    $group = [];
    foreach ($items as $item) {
        if ((!is_string($func) && is_callable($func)) || function_exists($func)) {
            $key = call_user_func($func, $item);
            $group[$key][] = $item;
        } elseif (is_object($item)) {
            $group[$item->{$func}][] = $item;
        } elseif (isset($item[$func])) {
            $group[$item[$func]][] = $item;
        }
    }

    return $group;
}
Examples
groupBy(['one', 'two', 'three'], 'strlen'); // [3 => ['one', 'two'], 5 => ['three']]

hasDuplicates

Checks a flat list for duplicate values. Returns true if duplicate values exists and false if values are all unique.

function hasDuplicates($items)
{
    return count($items) > count(array_unique($items));
}
Examples
hasDuplicates([1, 2, 3, 4, 5, 5]); // true

head

Returns the head of a list.

function head($items)
{
    return reset($items);
}
Examples
head([1, 2, 3]); // 1

last

Returns the last element in an array.

function last($items)
{
    return end($items);
}
Examples
last([1, 2, 3]); // 3

pluck

Retrieves all of the values for a given key:

function pluck($items, $key)
{
    return array_map( function($item) use ($key) {
        return is_object($item) ? $item->$key : $item[$key];
    }, $items);
}
Examples
pluck([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
], 'name');
// ['Desk', 'Chair']

pull

Mutates the original array to filter out the values specified.

function pull(&$items, ...$params)
{
    $items = array_values(array_diff($items, $params));
    return $items;
}
Examples
$items = ['a', 'b', 'c', 'a', 'b', 'c'];
pull($items, 'a', 'c'); // $items will be ['b', 'b']

reject

Filters the collection using the given callback.

function reject($items, $func)
{
    return array_values(array_diff($items, array_filter($items, $func)));
}
Examples
reject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) {
    return strlen($item) > 4;
}); // ['Pear', 'Kiwi']

remove

Removes elements from an array for which the given function returns false.

function remove($items, $func)
{
    $filtered = array_filter($items, $func);

    return array_diff_key($items, $filtered);
}
Examples
remove([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 0;
});
// [0 => 1, 2 => 3]

tail

Returns all elements in an array except for the first one.

function tail($items)
{
    return count($items) > 1 ? array_slice($items, 1) : $items;
}
Examples
tail([1, 2, 3]); // [2, 3]

take

Returns an array with n elements removed from the beginning.

function take($items, $n = 1)
{
    return array_slice($items, 0, $n);
}
Examples
take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3, 4, 5], 2); // [1, 2]

without

Filters out the elements of an array, that have one of the specified values.

function without($items, ...$params)
{
    return array_values(array_diff($items, $params));
}
Examples
without([2, 1, 2, 3], 1, 2); // [3]

orderBy

Sorts a collection of arrays or objects by key.

function orderBy($items, $attr, $order)
{
    $sortedItems = [];
    foreach ($items as $item) {
        $key = is_object($item) ? $item->{$attr} : $item[$attr];
        $sortedItems[$key] = $item;
    }
    if ($order === 'desc') {
        krsort($sortedItems);
    } else {
        ksort($sortedItems);
    }

    return array_values($sortedItems);
}
orderBy(
    [
        ['id' => 2, 'name' => 'Joy'],
        ['id' => 3, 'name' => 'Khaja'],
        ['id' => 1, 'name' => 'Raja']
    ],
    'id',
    'desc'
); // [['id' => 3, 'name' => 'Khaja'], ['id' => 2, 'name' => 'Joy'], ['id' => 1, 'name' => 'Raja']]

bubbleSort

Sorts an array using a Bubble sort algorithm.

This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

function bubbleSort($array) {
    $array = array_unique($array);
    $arrayLength = count($array);
    for ($i = 0; $i < $arrayLength - 1; $i++) { 
        $swapped = false;
        for ($j = 0; $j < $arrayLength - 1 - $i; $j++) {
            if ($array[$j] > $array[$j + 1]) {
                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
                $swapped = true;
            }
        }
        if (!$swapped) {
            break;
        }
    }
    return $array;
}
bubbleSort([44, 11, 7, 20, 12, 90, 35, 5]); // [5,7,11,12,20,35,44,90]

rotate

Rotates the array (in left direction) by the number of shifts.

Given the $shift index, it merges the array values after $shift with the values before $shift.

function rotate($array, $shift = 1)
{
    for ($i = 0; $i < $shift; $i++) {
        array_push($array, array_shift($array));
    }

    return $array;
}
rotate([1, 3, 5, 2, 4]); // [3, 5, 2, 4, 1]
rotate([1, 3, 5, 2, 4], 2); // [5, 2, 4, 1, 3]

Tags: PHP Array Filtering, Searching, Ordering, Modification all, any, deepFlatten, drop, findLast, findLastIndex, flatten, groupBy, hasDuplicates, head, last, pluck, pull, reject, remove, tail. take, without, orderBy

This article is licensed under the MIT License – see the License File for details

Categorized in: