0

I have any array with keys and values , I want to get the value of the key ,if key is equal to certain string.

When I use this code I am getting the last key value of array. I have the flexibility to change the array structure also if we want.

$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

foreach($grouparray   as $x=>$x_value){
          if($x=blue){
              $group_id=$x_value;

          }

      }

print_r($group_id);

I want to expect $group_id = 5;

JNevill
  • 46,980
  • 4
  • 38
  • 63
vyshnavi
  • 167
  • 1
  • 3
  • 16

2 Answers2

1

You have 2 problems in your if statement :

Replace if ($x=blue) { by if ($x == "blue") {

  1. Blue is a string so you need some quote
  2. = is to assign value, == or === are for comparaison.

But you shouldn't do a foreach loop to get your answer. If you just do $group_id = $grouparray['blue']; you will get what you want, not sure why you need a loop ?

Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36
0

your are missing quotes on blue.

$grouparray =[ "red" => "4" , "blue" =>"5" , "green" => "6"];

    foreach($grouparray as $x=>$x_value){
              if($x=="blue"){
                  $group_id=$x_value;

              }

          }

    print_r($group_id);
Vidal
  • 2,605
  • 2
  • 16
  • 32