【问题标题】:How to add multiple condition in PHP while looping如何在循环时在 PHP 中添加多个条件
【发布时间】:2021-12-14 11:44:34
【问题描述】:

如果其中一个条件为真,我打算停止此循环。但它不起作用......

有人有解决办法吗?

$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;

【问题讨论】:

标签: php while-loop do-while


【解决方案1】:

你可以试试if (($y!=$x)||($i!=$j)){ break; }

【讨论】:

    【解决方案2】:

    如果你想在一个条件为真时停止循环,那么你需要否定条件,比如

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

    如果你想在一个条件为真时停止循环,那么你也可以检查不等式

    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));        
    }
    

    【讨论】:

      【解决方案3】:

      你可以试试这个,希望能回答你的问题: 我看到您想将节点从 $i 迭代到 $j,或者直到主机 url 为 $x,然后 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;
        
      

      【讨论】:

        猜你喜欢
        • 2019-12-06
        • 2011-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-24
        • 2017-01-02
        • 2022-07-27
        相关资源
        最近更新 更多