2

I have an array that looks like this:

Array
    (
        [id] => 12
        [team_home_id] => 50
        [team_away_id] => 63
        [score_team_home] => 1
        [score_team_away] => 1
        [league_id] => 3
        [home_win_pred] => 50
        [draw_pred] => 26
        [away_win_pred] => 24
    )

Nowת I want to look from 3 keys (the 3 predictions: home_win_pred, draw_pred, away_win_pred) which one is the highest and then return that key.

I thought the code I used worked but it seems to return a different key if there is a duplicate value somewhere else in the array. So in the above example it returns team_home_id because this is also 50 as the highest in my 3.

the code I use:

array_search(max($arr[$x]['home_win_pred'], $arr[$x]['draw_pred'], $arr[$x]['away_win_pred']), $arr[$x]);

for the above example array it returns team_home_id instead of home_win_pred

How can I fix that?

dWinder
  • 11,597
  • 3
  • 24
  • 39
Awesom-o
  • 534
  • 6
  • 20

3 Answers3

1

Why not use a simple for loop:

$arr = array("team_home_id" => 50, "home_win_pred" => 50, "draw_pred" => 26, "away_win_pred" => 24);

$fields = array('home_win_pred','draw_pred','away_win_pred'); //field you want to loop over
$k = array_shift($fields); //take the first field
$max = $arr[$k]; // set the first value as max
foreach($fields as $filed) {
    if ($arr[$filed] > $max) { // if found a new max updated max an field
        $max = $arr[$filed];
        $k = $filed;
    }
}

Now, $k if the highest field: home_win_pred

dWinder
  • 11,597
  • 3
  • 24
  • 39
0

Here is one option, which approaches the problem by formally subsetting the array to only the keys of interest. Then, it uses array_keys() to find keys having the maximum value.

$keys = array('home_win_pred', 'draw_pred', 'away_win_pred');
$subset = array_intersect_key($arr, array_flip($keys));
$maxs = array_keys($subset, max($subset));

print_r($maxs);  // could be more than one key here

Array
(
    [0] => home_win_pred
)

Note that this will return multiple keys of the three keys of interest, should there be a tie for the highest value.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Why you get this result:

array_search — Searches the array for a given value and returns the first corresponding key if successful.

In your code,

max($arr[$x]['home_win_pred'], $arr[$x]['draw_pred'], $arr[$x]['away_win_pred'])

return 50 and the first occurrence of 50 is at key team_home_id.

GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26