Reputation: 1600
I am looking for a way to explicitly change some array keys as they will always be the same and the array length will always be the same and then output a single key based on the lowest value. Here is where I am at:
The array code itself look like this:
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,$low_score_5,$low_score_6,$low_score_7,$low_score_8);
Output example:
array(8) { [0]=> string(2) "11" [1]=> string(2) "15" [2]=> string(2) "13" [3]=> string(2) "12" [4]=> string(2) "18" [5]=> string(2) "16" [6]=> string(2) "16" [7]=> string(2) "14" }
So I want to change all 8 keys to each be a specific string. So I need to change the keys and then only output the key of the lowest value in the array. I can only at the moment output the value of the lowest in the array like so:
echo min($t);
And from the array above you can see that 11
is the lowest so that is the one I want to show BUT by ke and not value...
UPDATE
I have managed to set my keys and output both the keys with their retrospective pairs but I just want to show the lowest value by its key.
$t = array(
'a' => $low_score_1,
'b' => $low_score_2,
'c' => $low_score_3,
'd' => $low_score_4,
'e' => $low_score_5,
'f' => $low_score_6,
'g' => $low_score_7,
'h' => $low_score_8,
);
reset($t);
while (list($key, $val) = each($t)) {
echo "$key => $val\n";
}
The output of this looks like:
a => 11 b => 15 c => 13 d => 12 e => 18 f => 16 g => 16 h => 14
Upvotes: 0
Views: 34
Reputation: 10346
As mentioned it's a simple 'find minimum' problem. Only that you want to save the key of the minimum value.
$t = array($low_score_1,$low_score_2,$low_score_3,$low_score_4,$low_score_5,$low_score_6,$low_score_7,$low_score_8);
//Setting new keys
$t2 = array();
foreach($t as $key => $val){
$key2 = 'score_' . ($key+1);
$t2[$key2] = $val;
}
//Finding the minimum
$min = $t2['score_1'];
$min_key = 0;
foreach($t2 as $key => $val){
if($val < $min){
$min = $val;
$min_key = $key;
}
}
//output
print_r($t2);
echo $min; // the min value
echo $min_key; // the key of the min value
Upvotes: 1