Home > Software design >  How to prevent php foreach loop execute 2nd if statement when 1st if statement is executed?
How to prevent php foreach loop execute 2nd if statement when 1st if statement is executed?

Time:10-09

<?php
foreach($abc as $row)
{
    $msg = "";
    if($row < 100 && $msg=="")
    {
        $msg="Dog";
    }
    
    if($row < 100 && $msg!="")
    {
        $msg="Cat";
    }
}
echo $msg;
?>

Let say it loop 3 data, the output is :

Cat Dog
Cat Dog
Cat Dog

How to make the output become :

Dog
Cat
Cat

I try to add flag to the code but still it is not working:

foreach($abc as $row)
{
    $msg = "";
    $flag=0;
    if($row < 100 && $msg=="" && $flag==0)
    {
        $msg="Dog";
        $flag=1;
    }
    
    if(row < 100 && $msg!="" && $flag==0)
    {
        $msg="Cat";
        $flag=1;
    }
}

How to prevent php foreach loop execute 2nd if statement when 1st if statement is executed?

CodePudding user response:

Rather than a second if statement, you could use elseif.

elseif($row < 100 && $msg!="")

CodePudding user response:

One problem is with your flow. Within your loop you are setting $msg="", then checking whether it is blank and setting $msg="Dog", then checking that $msg is not blank (which it is not, because you just set it to be "dog") and setting $msg="Cat". It will always flow through those 3 steps.

More clarification might be needed on how you determine whether to output "dog" or "cat".

CodePudding user response:

Try the following:

<?php
foreach($abc as $row)
{
    $msg = "";
    if($row < 100 && $msg=="")
    {
        $msg="Dog";
        break;
    }
    
    if($row < 100 && $msg!="")
    {
        $msg="Cat";
        break;
    }
}
echo $msg;
?>

  •  Tags:  
  • php
  • Related