1

Trying to return the array where the key "distance" contains the maximum value, as opposed to just returning the value.

ie. from:

[0] => Array
    (
        [pid] => 1
        [type] => lj
        [distance] => 211849216
        [maxspeed] => 277598944
        ...
    )
[1] => Array
    (
        [pid] => 1
        [type] => lj
        [distance] => 230286752
        [maxspeed] => 289118816
        ...
    )
[2] => Array
    (
        [pid] => 1
        [type] => lj
        [distance] => 230840928
        [maxspeed] => 298438336
        ...
    )
...

I wish to get [2]:

(
    [pid] => 1
    [type] => lj
    [distance] => 230840928
    [maxspeed] => 298438336
    ...
)

I've been able to get the max value with the following:

function max_dist($a) {
    return $a["distance"];
}
$jump = max(array_map("max_dist", $jumps)));

But unlike how elegantly simple it is with JS/underscore:

var jump=_.max(jumps,function(o){
    return +o.distance;
});

it only returns the max distance value.

I have to just be missing something simple in PHP!

1 Answer 1

1
function max_dist($array) {
    $maxIndex = 0;
    $index = 0;
    $maxValue = $array[0]['distance'];
    foreach( $array as $i){
        if($i['distance'] > $maxValue){
            $maxValue = $i['distance'];
            $maxIndex = $index;
        }
    $index++;
    }
    return $array[$maxIndex];
}
$jump = max(array_map("max_dist", $jumps)));
Sign up to request clarification or add additional context in comments.

2 Comments

Not at all elegant/simple like it is in JS but I guess it gets the job done just fine. Thanks for the quick response sir!
This code is meant to be added to the function max_dist($array) but I had a problem editing this on mobile :D

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.