Home >Backend Development >PHP Tutorial >Questions about conditional expressions in while loop

Questions about conditional expressions in while loop

WBOY
WBOYOriginal
2016-08-04 09:22:182018browse

<code>while ($i = 'AAA' && $j = 'BBB') {
    var_dump($i, $j);
    sleep(3);
}

</code>
<code class="php">输出结果
bool(true)
string(3) "BBB"</code>
<code>
-------------------------------------------------------------

在写一个后台监听程序的时候使用了while循环,于是纠结了一下`while`中的条件表达式</code>
  1. For the above code, I expected to output AAA BBB, but why is it true BBB

  2. Look at this code

    <code>while($ret = 100) {
        var_dump($ret) // output:100
    }</code>

    How does the conditional expression $ret=100 in the brackets here result in true or false. What I want is to first assign the value 100 to the $ret variable, and then perform a Boolean conversion on $ret to get the result.

    Hope everyone can help clear up the confusion. Thank you.

Reply content:

<code>while ($i = 'AAA' && $j = 'BBB') {
    var_dump($i, $j);
    sleep(3);
}

</code>
<code class="php">输出结果
bool(true)
string(3) "BBB"</code>
<code>
-------------------------------------------------------------

在写一个后台监听程序的时候使用了while循环,于是纠结了一下`while`中的条件表达式</code>
  1. For the above code, I expected to output AAA BBB, but why is it true BBB

  2. Look at this code

    <code>while($ret = 100) {
        var_dump($ret) // output:100
    }</code>

    How does the conditional expression $ret=100 in the brackets here result in true or false. What I want is to first assign the value 100 to the $ret variable, and then perform a Boolean conversion on $ret to get the result.

    Hope everyone can help clear up the confusion. Thank you.

<code>if (($i = 'AAA') && ($j = 'BBB')) {
    var_dump($i, $j);
}
</code>

Attention && Priority

Operator logic problem, price brackets are wrong

<code class="php">while (($i = 'AAA') && ( $j = 'BBB')) {


    var_dump($i, $j);// true bbbbb
    sleep(3);
}</code>

  1. The comma operator causes the output bbb, V=1,2. At this time, v is 2
    2. An infinite loop. Convert to boolea can be ret = ret && true

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn