views:

43

answers:

3

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

However, 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?

A: 
<?php
  $i= 11;
  function get_num() {
    global $i;
    return (--$i >= 0) ? $i : false;
  }
  while(($num = get_num())!==false) {
    echo "Number: $num\n";
  }
?>
Cam
A: 

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 : TRUE if $a is equal to $b.
$a === $b : Identical : TRUE if $a is equal to $b, and they are of the same type.

Pascal MARTIN
+1  A: 
while( ($num = get_num()) !== false ) {

extra = forces type check as well.

webbiedave