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):
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)
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With