在foreach中的if语句,声明不适用[重复]

This question already has an answer here:

I'm processing a json from an url and showing some data. The problem is that I just want to display two accounts with certain id's but when I execute the following code is echoing the name of each account and not selecting the ones I choosen in the if-statement.

foreach ($data as $row) {

    $id = $row->id;
    $account = $row->account;
    $time = date("Y-m-d H:i:s");

    if ($id = 100) {echo $account;}
    elseif ($id = 120) {echo $account;}
    else {}

}

The Json is like

{"id":120,"Name":"Companytest"},
{"id":121,"Name":"BensonTillis"},
{"id":123,"Name":"JSBrothers"}

Thank you.

</div>

You need to use == instead of = in your if statements.

When you are comparing numbers you need to use "==" as it is one of the comparison operators http://php.net/manual/en/language.operators.comparison.php

The single "=" is an assigment operator and sets $id to the value on the right hand side. http://php.net/manual/en/language.operators.assignment.php

You should use a double equals == instead of single = in your 'if' condition

This is because you are actually assigning $id to be = to 100,

to fix that simply add a second = inside your if statment like so:

if ($id == 100) {echo $account;}

Also. I have learned to do my if statements like:

if (100 == $id) {echo $account;}

this simply prevents the possibility of assigning the variable and instead will cause:

syntax error, unexpected '='

which is easier to debug