简体   繁体   中英

if statement in for loop only executing once

I am trying to compare retrieved json data from a database, and there is a nested if statement within the for loop. The problem is that the 'if' statement is only executing once (when it finds the first record in the database), and then it's being skipped in further iterations. I am using PHP and MySQL (for the db).

for ($i=0;$i<count($obj['datalist']);$i++){
    $name[]=$obj['datalist'][$i]['name'];
    if ($name[$i]===$row['user']){ //once it finds the first record, it goes to the 'else' part for the rest of the for loop
    //if ($row['user']==$name[$i]){
        echo "<p class='testclass'>".$name[$i] ." is in the database! ".$i."<br />";
    } else {
        echo "<p class='testclass'>". $name[$i] ." is NOT in the database! ".$i."</p>";
    }
}

Code can be also found here .

Should your code not be this:

$name=$obj['datalist'][$i]['name'];

//if ($name[$i]===$row['user']){
if ($row['user']==$name){

You are already getting the name from the collection, and you want to compare it with your $row isnt?

You are recreating the same $name in every loop.

you should use this line instead :

$name[$i]=$obj['datalist'][$i]['name'];

Or if you don't need to reuse the $name collection/array then you can simply overwrite it using :

$name = $obj['datalist'][$i]['name'];

and modify your if statement according to this variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM