0

I have following array structure. I'd like to get max value in array, and if values in array are same to unset this array.

   Array(

        [499670] => Array
            (
                [499670] => 1299.00
                [503410] => 1299.00
                [528333] => 1299.00
                [645862] => 0.00
            )

        [499671] => Array
            (
                [499671] => 1149.00
                [503408] => 1149.00
                [528329] => 1500.00
                [645858] => 0.00
            )

        [499672] => Array
            (
                [499672] => 0.00
                [503406] => 0.00
                [528324] => 0.00
                [645850] => 0.00
            )
)

I want to get the following result

   Array(

                [499670] => 1299.00 >>> one of values in first array
                [528329] => 1500.00 >>> max value in second array
                {third array was removed, because all values are same}

)
2
  • What's your current code? It might just need a small tweak. Which part is giving you trouble?
    – Mog
    Commented Mar 20, 2014 at 16:37
  • Just walk through each array and keep a maxIndex and maxValue that relate to each other?
    – Uxonith
    Commented Mar 20, 2014 at 16:38

1 Answer 1

3

Iterate through your array, use array_unique() to check if all the values are the same. If not, find the max value using max():

$result = array();

foreach ($data as $key => $subarr) {
    if (count(array_unique($subarr)) === 1) {
        unset($data[$key]);
    } else {
        $result[] = max($subarr);
    }
}

print_r($result);

Output:

Array
(
    [0] => 1299.00
    [1] => 1500.00
)

Demo

2
  • 1
    I believe the , PHP_EOL has nothing to do here ;-)
    – svvac
    Commented Mar 20, 2014 at 16:40
  • @swordofpain: That was initially used with the echo statement to output them in new lines. But I've edited the answer to use an array instead ;) Commented Mar 20, 2014 at 16:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.