Arrays in PHP part 1

Arrays in PHP part 1

·

3 min read

Hey, guys! You know when you need to do something and you have to search the internet for code snippets, some work and some don't. So this is the first part in a series of snippets where I will write code snippets that I think are quite useful.

Searching in array

To search in the array you can use it instead array_filterof foreach / for loop

public static function search($array, $searching, $key = 'id'): array
{
    $filter = function ($item) use ($searching, $key) {
        return $item[$key] == $searching;
    };

    return array_filter($array, $filter);
}

The array_filter function in PHP is a function that filters the elements of an array using a user-supplied callback function. It returns a new array containing only the elements that pass the test specified by the callback function.

Is a useful function for filtering the elements of an array based on a custom condition. It can be used to remove elements from an array, extract specific elements from an array, or transform the elements of an array in some way.

Check condition against multidimensional array

To verify a condition in a multidimensional array the foreach loop is often used, but it is also possible to use array_reduce as in the example bellow

public static function check($array, $searching, $key = 'id'): bool
{
    $callback = function ($carry, $item) use ($searching, $key) {
        if ($item[$key] == $searching) {
            return true;
        }

        return $carry;
    };

    return array_reduce($array, $callback, false);
}

The array_reduce function in PHP is a function that reduces an array to a single value by applying a user-supplied function to each element in the array, iteratively reducing the array to a single value.

It can be used for a variety of tasks, such as summing the elements of an array, concatenating the elements of an array into a string, or applying a custom operation to the elements of an array. It is a useful function for performing complex operations on arrays concisely and efficiently.

Compare two arrays

If you ever need to compare two arrays, here's a pretty simple way to do it array_udiff

public static function diff($array1, $array2, $key = 'id'): array
{
    $callback = function ($a, $b) use ($key) {
        return $a[$key] <=> $b[$key];
    };

    return array_udiff($array1, $array2, $callback);
}

The array_udiff function in PHP is used to compare two or more arrays and returns an array containing only the values from the first array that are not present in any of the other arrays. The comparison of the array values is done using a user-supplied callback function.

It can also be used to compare more than two arrays by specifying additional arrays as arguments. The function will return an array containing only the values that are present in the first array but not in any of the other arrays.

That's all for now. Have a nice day.

ko-fi