Search code examples
phparrayscomputer-science

Quick Way to Find the Largest Array in a Multidimensional Array?


Situation: I have a multidimensional array with a variable number of elements. e.g.

array(N) {
    0 => array(3) { ... },
    1 => array(8) { ... },
    2 => array(1) { ... },
    ...
    M => array(12) { ... },
    ...
    N-1 => array(7) { ... }
}

And I would like to find the maximum number of elements in this sub-array (in the example above, it would be 12). A straightforward solution would be an O(N) linear search.

<?php
function max_length($2d_array) {
    $max = 0;
    foreach($2d_array as $child) {
        if(count($child) > $max) {
            $max = count($child);
        }
    }
    return $max;
}

However, I can't help but wonder if there's some clever trick to optimize this lookup. So my question is a two-parter (though an answer to either part would solve it):

  • Is there an algorithm that performs this search faster than O(N) without requiring special requirements (pre-sorted, etc)?
  • Is there an obscure PHP function somewhere that will perform this search in native code rather than my userland PHP script?

Solution

  • You can use this : https://www.php.net/manual/ro/function.max.php

    $test = array(
               array('G', 'M', 2, 2),
               array(1, 2222, 3)
             );
     $arr = max($test);
    

    // output ->

    array(4) {
      [0]=>
      string(1) "G"
      [1]=>
      string(1) "M"
      [2]=>
      int(2)
      [3]=>
      int(2)
    }