Categories
PHP Development

Useful PHP Functions, Arrays, array_filter()

The below code probably shows example of the most useful usage of array_filter() function, where you can use both associative array key and value, and on top of that, also inject external parameter to callback function.

$score = 150;
$players = [
    'john' => 92,
    'adam' => 150,
    'kate' => 138,
    'robert' => 150,
    'sylvia' => 76,
    'clair' => 141,
    'ann' => 150,
    'mike' => 78
];

$results = array();

$results = array_filter($players,  function ($val, $key) use($score) {
    if($val == $score && $key == 'adam') {
        return  $val;
    }

//    if($val == $score) {
//        return  $val;
//    }
//
//    if($key == 'kate') {
//     return  $val;
//    }

}, ARRAY_FILTER_USE_BOTH);

//possible flags: ARRAY_FILTER_USE_BOTH or ARRAY_FILTER_USE_KEY

print_r($results);

Below, result of the above code:

Array
(
    [adam] => 150
)

By uncommenting different parts of if condition – for example purposes – we have access to associative array key, value and external parameter: use
In fact array_* functions are rather slower, than – let’s say – foreach loop, but sometimes they can produce cleaner code.

Based on my experience I can only say, that too extensive usage of array_* functions (sometimes one inside another one, and with referenced variables) can slow down maintenance of code or make code modifications much more time consuming.