I have multiple arrays that need to be compared on how many items they contain and select the array with the highest value (= the array with the most items in it)
E.g. I have 3 arrays:
$a_arr = array( '0' => '45', '1' => '50', '2' => '100' );
$b_arr = array( '0' => 'apple' );
$c_arr = array( '0' => 'toyota', '1' => 'ferrari', );
Now I need to compare the number of items in these arrays and select the array with the highest number of items. So, the highest in these case would be $a_arr
with 3 items.
How to do that the most efficient way in PHP?
3 Answers 3
You can use max() to determine the longest array.
$longest = max($a_arr, $b_arr, $c_arr);
// Will return the array with highest amount of items ($a_arr)
Combine it with count() to get the amount of items in the longest array.
$longest = max(count($a_arr), count($b_arr), count($c_arr));
// Will return the max number of items (3 in this case; length of $a_arr)
-
Thanks, but couldn't it be done using something simpler and without creating additinoal array?user2984974– user29849742013年11月12日 20:52:12 +00:00Commented Nov 12, 2013 at 20:52
-
@user2984974 Just fiddled around a bit and there is, see updated answer.Oldskool– Oldskool2013年11月12日 21:00:57 +00:00Commented Nov 12, 2013 at 21:00
-
Incredible, I shall test it.jacouh– jacouh2013年11月12日 21:04:38 +00:00Commented Nov 12, 2013 at 21:04
-
-
@GottliebNotschnabel You're right, that would return the maximum amount of items in any of the arrays. Updated the answer.Oldskool– Oldskool2013年11月12日 21:09:11 +00:00Commented Nov 12, 2013 at 21:09
I propose one method:
$a_arr = array( '0' => '45', '1' => '50', '2' => '100' );
$b_arr = array( '0' => 'apple' );
$c_arr = array( '0' => 'toyota', '1' => 'ferrari', );
$result = $a_arr;
$nmax = count($a_arr);
$n = count($b_arr);
if($n > $nmax)
{
$nmax = $n;
$result = $b_arr;
}
$n = count($c_arr);
if($n > $nmax)
{
$nmax = $n;
$result = $c_arr;
}
//
// compare other arrays...
//
//
// maximal elements: $nmax, $result here is the array with the maximum of items.
//
-
1Laborious but all in all correct (I actually assume something like this is what the
max()
function does internally). +1dialogik– dialogik2013年11月12日 21:11:52 +00:00Commented Nov 12, 2013 at 21:11
Just for fun:
array_multisort(($c=array_map('count',(compact('a_arr','b_arr','c_arr')))),SORT_DESC,$c);
echo key($c) . ' = ' . current($c);