Hello all.
For each sub array in $arr_rgb (Fig.01) I have to find: If element with $key number 1 is the highest number in this sub array, then return the $key number of the sub array (Fig.03 and Fig.04. So far, I can find highest number for each sub array – fig.02
In the attached image the “trouble” I have is explained.
And the code that I use so far:
<?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; foreach ($arr_rgb as $key => $value) { $resultMax[$key] = max($value); } } } echo "<pre>"; var_dump($resultMax); 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>";
Advertisement
Answer
Determining the maximum using max
only properly works for integers, so I would use array_map
with hexdec
to achieve that.
Then all it needs is a comparison of the value at position 1 with that maximum, and if they are the same, then the index gets added to the result array:
$result = []; foreach($hex_splited as $key => $value) { if(hexdec($value[1]) == max(array_map('hexdec', $value))) { $result[] = $key; } } var_dump($result);
This gets you 0, 1, 3
as result. (As IMHO it should be, according to your stated requirements – the value 00
at position 1 in the first sub-array is also the maximum of all values in that sub-array. If you need to exclude 0 values, then you’ll have to modify accordingly.)
EDIT:
if all elements are equal, then return nothing
Okay, that can also be implemented quite easily – we use array_count_values
, and if the count of that is only 1, then that means all the elements had the exact same value.
So then it becomes
foreach($hex_splited as $key => $value) { if(count(array_count_values($value)) != 1 && hexdec($value[1]) == max(array_map('hexdec', $value))) { $result[] = $key; } }
With that, you get [1, 3]
as $result here.