Search code examples
phpmultidimensional-arraymaxarray-algorithms

Get highest value from multidimensional array


Here is my multidimensional array:

$arrOrg = [2, 3, [5, 7, 1], 100, [6, 9, [14, 95]], 78];

I want to get the highest value from this array.

Here is what I have tried so far:

$highest = 0;
function getHighest($arr) {
    for ($i = 0; $i < count($arr); $i++) {
        if (is_array($arr[$i])) {
            getHighest($arr[$i]);
        } else {
            if ($arr[$i] > $arr[$i + 1]) {
                $highest = $arr[$i];
            } else {
                $highest = $arr[$i + 1];
            }
        }
    }
    return $highest;
}
echo getHighest($arrOrg);

But it is giving an incorrect result: 78

Can you help me out?


Solution

  • Maybe something like this:

    $arrOrg = [2, 3, [5, 7, 1], 100, [6, 9, [14, 95]], 78];
    $json   = json_encode($arrOrg);
    $json   = str_replace(array('[', ']'), "", $json);
    $arr    = explode(",", $json);
    
    echo $maximum = max($arr);
    

    EDIT after Vahe Galstyan comment

    $arrOrg = array(
        2, 
        3,
        array(5, 7, 1), 
        100,
        array(
            6, 
            9, 
            array(14, 95)
        ), 
        78
    );
    
    $json = json_encode($arrOrg);
    $json = str_replace(array('[', ']'), "", $json);
    $arr  = explode(",", $json);
    
    echo $maximum = max($arr);