1

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?

dialogik
9,58218 gold badges78 silver badges122 bronze badges
asked Nov 12, 2013 at 20:46

3 Answers 3

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)
answered Nov 12, 2013 at 20:49
9
  • Thanks, but couldn't it be done using something simpler and without creating additinoal array? Commented Nov 12, 2013 at 20:52
  • @user2984974 Just fiddled around a bit and there is, see updated answer. Commented Nov 12, 2013 at 21:00
  • Incredible, I shall test it. Commented Nov 12, 2013 at 21:04
  • It should be $longest = max(count($a_arr), count($b_arr), count($c_arr));, see here. Commented Nov 12, 2013 at 21:05
  • @GottliebNotschnabel You're right, that would return the maximum amount of items in any of the arrays. Updated the answer. Commented Nov 12, 2013 at 21:09
1

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.
//
answered Nov 12, 2013 at 20:53
1
  • 1
    Laborious but all in all correct (I actually assume something like this is what the max() function does internally). +1 Commented Nov 12, 2013 at 21:11
1

Just for fun:

array_multisort(($c=array_map('count',(compact('a_arr','b_arr','c_arr')))),SORT_DESC,$c);
echo key($c) . ' = ' . current($c);
answered Nov 12, 2013 at 20:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.