1

Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

Output should be like:

max(12.9) min(10)

2 Answers 2

2

Another option

<?php

function array_rotate( $array )
{
    $rotated = array();
    foreach ( $array as $rowIndex => $col )
    {
        foreach ( $col as $colIndex => $value )
        {
            $rotated[$colIndex][$rowIndex] = $value;
        }
    }
    return $rotated;
}

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

$ar = array_rotate( $ar );

echo max( $ar[2] ), "\n", min( $ar[1] );
Sign up to request clarification or add additional context in comments.

Comments

1
<?php
$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));
function col($tbl,$col){
    $ret = array();
    foreach ($tbl as $row){
        $ret[count($ret)+1] = $row[$col];
    }
    return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>

is this what you look for? I guess its not the most efficient way.

3 Comments

I'd like to comment that this approach can break unless you have a completely rectangular 2d array. as the input.
why do you do $ret[count($ret)+1] = $row[$col]; What's wrong with $ret[] = $row[$col];
tom: I just tried to add element at the very end of the $ret array. I did not know $ret[] notation :D BaileyP: unsure of what would be the break condition - input array has 3 elements, every element is a 4 element array.

Your Answer

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