sam
sam

Reputation: 10084

Find highest max() of mixed array

Ive got an array outputted from the DB

Array

    (
        [0] => Array
            (
                [name] => Fernando Alonso
                [time1] => 3.25
                [time2] => 3.25
                [time3] => 3.5
            )

        [1] => Array
            (
                [name] => Jenson Button
                [time1] => 34
                [time2] => 41
                [time3] => 41
            )
    )

what i want to do is for each driver output their name and their fastest time somthing like

Fernando Alsonso, time3 - 3.5

Jenson Button, time2, time3 - 41

I was playing around using max() but was having trouble getting it to work as it was having trouble as the first element is a string, rather than a int / num,

any idea how i would write this function ?

Upvotes: 0

Views: 123

Answers (1)

RMcLeod
RMcLeod

Reputation: 2581

Okay here you go, you were right to try with max()

function get_highest_time($driver) {
    // First find the highest time
    $highest_time = max($driver['time1'], $driver['time2'], $driver['time3']);
    // now find all of the array keys that match that time
    $times = array_keys($driver, $highest_time);
    // now turn that array of keys into a string and add the highest time to the end
    return implode(', ', $times) . ' - ' . $highest_time;
}

foreach ($arr as $driver) { // Where $arr is your array of drivers
    print $driver['name'] . ': ' . get_highest_time($driver) . '<br />';
}

EDIT:

Just noticed you said you want the driver's fastest time, which would surely be the lowest number? If that is the case swap max() for min()

Upvotes: 1

Related Questions