arrays - PHP array_column with array_filter -


i doing echo minimum value in array...

$array = [ [     'a' => 0,     'f' => 0,     'f' => 0,     'l' => 61.60 ], [     'a' => 38,     'f' => 0,     'f' => 0,     'l' => 11.99 ], [     'a' => 28,     'f' => 0,     'f' => 0,     'l' => 3.40  ] ];  $min = min(array_column($array, 'a'));  echo $min; 

now want exclude 0 results, know can use array_filter achieve need process array twice?

yes, do:

$min = min(array_filter(array_column($array, 'a'))); 

it iterate array 3 times, once each function.

you can use array_reduce in 1 iteration:

$min = array_reduce($array, function ($min, $val) {     return $min === null || ($val['a'] && $val['a'] < $min) ? $val['a'] : $min; }); 

whether that's faster or not must benchmarked, php callback function may after slower 3 functions in c.

a more efficient solution without overhead of function call ol' loop:

$min = null; foreach ($array $val) {     if ($min === null || ($val['a'] && $val['a'] < $min)) {         $min = $val['a'];     } } 

in end need benchmark , decide on correct tradeoff of performance vs. readability. in practice, unless have positively humongous datasets, first one-liner fine.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -