Pavlin Dimtroff
Pavlin Dimtroff

Reputation: 25

max() function can't find correct value. php

I'm trying to get the max value in the array. But using max() for the entire array it can't find the highest value:

enter image description here

The return Key is 2, which is not the correct key, obviously the highest value is in array(3). Please help me to find my mistake. Here bellow is my code:

<?php
$hex_splited = [
        ['00','00','00'], 
        ['10', '11', '10'], 
        ['F0', '1A', 'C3'],
        ['0F', 'FE', 'F4'],
       ];
$arr_rgb = [];
$count2 = count($hex_splited);
for ($i=0; $i < $count2; $i++) { 
    $inn_count = count($hex_splited[$i]);
    for ($j=0; $j < $inn_count; $j++) { 
            $val = hexdec($hex_splited[$i][$j]);
            $arr_rgb[$i][$j] = $val;
    }
}
$max = max($arr_rgb);
var_dump($max);
$key = array_search($max, $arr_rgb);
echo "<pre>";
echo "array key is: " . $key;
echo "</pre>";

    echo "<table border='1'>";
for ($m=0; $m < $count2; $m++) {
    echo "<tr>";
    for ($k=0; $k < $inn_count; $k++) { 
        echo "<td>";
        echo $arr_rgb[$m][$k];
        echo "</td>";
    }
    echo "</tr>";
}
echo "</table>";

Upvotes: 0

Views: 82

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

The problem is that max() doesn't always behave as you would expect when using multidimensional arrays.

This code does the processing in two stages, first finds the max value. As this is only a 2 dimensional simple array, you can use...

$max = max(array_map("max", $hex_splited));

This applies max to each of the sub arrays and then gets the max of those values.

So in your case, this will be 'FE'. Then as part of the loop which converts the data to decimal, it compares the original value with the max already found and stores the key...

$key = 0;
for ($i=0; $i < $count2; $i++) {
    $inn_count = count($hex_splited[$i]);
    for ($j=0; $j < $inn_count; $j++) {
        $val = hexdec($hex_splited[$i][$j]);
        $arr_rgb[$i][$j] = $val;
        // Check if found the max value
        if ( $max == $hex_splited[$i][$j] ) {
            $key = $i;
        }
    }
}

Upvotes: 2

Related Questions