PHP loose typing in while loop comparison
Given the following code snippet:
  $i= 11;
  function get_num() {
    global $i;
    return (--$i >= 0) ? $i : false;
  }
  while($num = get_num()) {
    echo "Number: $num\n";
  }
Results in the following output:
Number: 10
Number: 9
Number: 8
Number: 7
Number: 6
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1
How开发者_运维问答ever, I also want it to output Number: 0 - but the while loop evaluates 0 as being false, so the loop never gets to that point. How do I get the loop to terminate only on an explicit false?
while( ($num = get_num()) !== false ) {
extra = forces type check as well.
<?php
  $i= 11;
  function get_num() {
    global $i;
    return (--$i >= 0) ? $i : false;
  }
  while(($num = get_num())!==false) {
    echo "Number: $num\n";
  }
?>
You have to do a comparison that compares the types, and not only the values -- which means using the === or !== operators, instead of == or !=.
So, you could use something like :
while(($num = get_num()) !== false) {
    echo "Number: $num\n";
}
With this, 0 will not be considered as the same thing as false.
As reference : Comparison Operators (quoting)
$a == $b: Equal :TRUEif$ais equal to$b.$a === $b: Identical :TRUEif$ais equal to$b, and they are of the same type.
I noticed that you are using global.  Some devs scream about using global when not necessary.  Also, you can leave out the parentheses if you write false!== before your $num declaration (no big deal, just a note).
Option 1
function get_num() {
    static $i=11;  // effectively only declare the value once
    return (--$i >= 0) ? $i : false;
}
while(false!==$num=get_num()){
    echo "Number: $num\n";  // $i is NOT available outside the scope of the function.
}
Option 2
function get_num($i) {
    return (--$i >= 0) ? $i : false;
}
$num=11;  // declare in global scope
while(false!==$num=get_num($num)){  // pass it to function as an argument
    echo "Number: $num\n";
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论