0

I have an array like this using php:

$array = array(
  array("id" => "1", "name" => "name1"),
  array("id" => "2", "name" => "name2"),
  array("id" => "3", "name" => "name3"),
  array("id" => "4", "name" => "name4"),
  array("id" => "5", "name" => "name5"),
  array("id" => "6", "name" => "name6"),
  array("id" => "7", "name" => "name7"),
  array("id" => "8", "name" => "name8"),
);

What I want to do is be able to select a name based on the id number. I used the following code:

foreach ($array as $value)
{
  if($value['id'] = 5 ){
    echo  $value['name'] ."<p>";
  }
}

I was expecting the result to be name5 but it displays the following:

name1

name2

name3

name4

name5

name6

name7

name8

I guess I did something wrong with the if statement. I was expecting it to display name5 only as that is the only array with id number "5" but for some reason it is display all the names even if the id number is not 5. What am I doing wrong here?

Thanks.

MasterA
  • 13
  • 1
  • 4
  • 1
    `=` is not `==` and `5` is not `'5'` – Alex Sep 17 '18 at 20:26
  • When building `$array`, consider indexing it by the `id` value if possible. That way you can just refer to `$array[5]` to get what you need without iterating. – Don't Panic Sep 17 '18 at 20:34

3 Answers3

1

if($value['id'] = 5 ){

The above line sets $value["id"] to 5

You should use === for comparison

if($value['id'] === 5 ){

The === would compare the type of the variable as well as the value, so you should make sure the id field in the $array is of type number

Velimir Tchatchevsky
  • 2,812
  • 1
  • 16
  • 21
0

You are missing comparison instead you added a variable

foreach ($array as $value)
{
  if($value['id'] == 5 ){
    echo  $value['name'] ."<p>";
  }
}
jvk
  • 2,133
  • 3
  • 19
  • 28
0

there is "==" missing in your code. "==" is used for comparison while "=" is an assignment to assign a value to the variable. Try this

foreach ($array as $value)
{
  if($value['id'] == 5 ){
    echo  $value['name'] ."<p>";
  }
}