Home > Software design >  How to add multiple condition in PHP while looping
How to add multiple condition in PHP while looping

Time:10-30

I intend to stop this loop if one of this condition is true. But it is not working...

Is any one have the solution?

$x="sbplay1.com";
$y="";
$i=0;
$j=4;
$myUrl="No match found";
while(($y!=$x)||($i!=$j)){
    $node = $dom->getElementsByTagName('a')->item($i  );
    $myUrl = $node->getAttribute("href");
    $y= (parse_url($myUrl, PHP_URL_HOST));        
}   
echo $myUrl;

CodePudding user response:

You can try if (($y!=$x)||($i!=$j)){ break; }

CodePudding user response:

If you want to stop the loop if one condition is true, then you need to negate the condition, like

while (!(($y!=$x)||($i!=$j))){
    $node = $dom->getElementsByTagName('a')->item($i  );
    $myUrl = $node->getAttribute("href");
    $y= (parse_url($myUrl, PHP_URL_HOST));        
}

If you want to stop the loop if exactly one condition is true, then you can check for inequality as well

while ((($y!=$x)||($i!=$j)) && (($y!=$x) !== ($i!=$j))){
    $node = $dom->getElementsByTagName('a')->item($i  );
    $myUrl = $node->getAttribute("href");
    $y= (parse_url($myUrl, PHP_URL_HOST));        
}

CodePudding user response:

You can try this, hope will answer your question: I see you want iterate the nodes from $i to $j, or until the host url is $x, then echo $myUrl;

$x="sbplay1.com";
$y="";
$i=0;
$j=4;
$myUrl="No match found";
for ($i = 0; $i <= 4; $i  ) {
    $node = $dom->getElementsByTagName('a')->item($i);
    $myUrl = $node->getAttribute("href");
    $y = parse_url($myUrl, PHP_URL_HOST);
    if ($x == $y) break;
}
echo $myUrl;
  
  • Related