phparraysmultidimensional-array

Compare two elements in each row of a 2d array


I have an Multidimensional Array.

Array ( 
[0] => Array ( 
    [0] => 116.01 
    [1] => 146.00 ) 
[1] => Array ( 
    [0] => 92.00 
    [1] => 122.02 ) 
[2] => Array ( 
    [0] => 308.00 
    [1] => 278.00 ) )

I want to compare using less than or greater than, [0][0] with [0][1] and then [1][0] with [1][1] and so on. I'm dummy with multidimensional array


Solution

  • You could loop through your first array like so:

    foreach ($array as $key => $subArray) {
        //do stuff
    }
    

    Then inside that loop you have access to each individual array. So in there you could do something like this:

    if ($subArray[0] < $subArray[1]) {
        echo '1 is biggest';
    } elseif ($subArray[0] > $subArray[1]) {
        echo '0 is biggest';
    } else {
        echo '1 and 0 are equal';
    }
    

    So your total code would look something like this:

    foreach ($array as $key => $subArray) {
    
        echo 'For array with key ' . $key . ':';
    
        if ($subArray[0] < $subArray[1]) {
            echo '1 is biggest';
        } elseif ($subArray[0] > $subArray[1]) {
            echo '0 is biggest';
        } else {
            echo '1 and 0 are equal';
        }
    }