Zestyy99
Zestyy99

Reputation: 307

How to compare a value within a variable with a value in an associative array?

If i've got an array:

$grades = array("A+"=>"5", "A"=>"4", "B"=>"3", "C"=>"2", "D"=>"1", "F"=>"0");

and i've got a variable:

$score = 5;

is there a way to compare the value within the $score variable and the $grades array and store the result in a variable $grade?

So in the example above the value in $grade should be A+?

Upvotes: 2

Views: 68

Answers (4)

Syscall
Syscall

Reputation: 19780

You could use array_search() to get the first corresponding key for a value:

$grades = array("A+"=>"5", "A"=>"4", "B"=>"3", "C"=>"2", "D"=>"1", "F"=>"0");
$score = 5;
$grade = array_search($score, $grades);
echo $grade; // A+

Upvotes: 3

chinloyal
chinloyal

Reputation: 1141

$grades = array("A+"=>"5", "A"=>"4", "B"=>"3", "C"=>"2", "D"=>"1", "F"=>"0");
$score = "5";
$grade = "";

foreach($grades as $key=> $val){
    if($score == $val)
        $grade = $key;
}

echo $grade;

Upvotes: 3

Eddie
Eddie

Reputation: 26844

You can use array_flip to exchanges all keys with their associated values in an array. array_flip the array and you can reuse the array multiple times.

$grades = array("A+"=>"5", "A"=>"4", "B"=>"3", "C"=>"2", "D"=>"1", "F"=>"0");
$grades = array_flip($grades); 
$score = 5;

echo $grades[$score] . "<br />";
echo $grades[4] . "<br />";
echo $grades[1] . "<br />";

This will result to

A+
A
D

Documentation: http://php.net/manual/en/function.array-flip.php

Upvotes: 4

kevinniel
kevinniel

Reputation: 1106

For an associative array, you have to iterate with the foreach function as following :

foreach($grades as $key => $value){
    if($score === intval($value)){
        $grade = $key;
        break;
    }
}

for associative array, use : $key => $value. This way in your exemple, during the first iteration, $key will be "A+" and $value will be "5".

For more informations, you can go look here ;p

Upvotes: 3

Related Questions