Question

Maybe if I dont know smth, but this one works:

$city = City::find(1);
$city->visible = 0;

This does not:

if ($city->visible = 0) {
}

This works

if ($city->visible = ***) {
}
// where *** - number, except 0 / letter

Why? Does it return false?

My bad: thought it would assign value to variable in object.

Was it helpful?

Solution

This is an expression

$city->visible = 0

Which evaluates to 0. So, you're essentially writing

if (0) { ... }

But 0 is a falsey value in PHP, so the IF block will never be called


Compare that to

$city->visible = 1

Which evaluates to

if (1) { ... }

1 is a truthy value in PHP, so the block IF will be called


Per your comment, please see

$a = 1;      // this silently evaluates to 1; no visible output
echo $a = 0; // 0
echo $a;     // 0

OTHER TIPS

Basic rules of PHP: the return value of an assignment operation is the value being assigned.

So when you do

if ($foo = 0) {
}

PHP will assign 0 to $foo, and then return 0 to the if() test. Since 0 is a false value, the if() test fails, and any code within it is not executed.

This is the exact same mechanism that allows

$foo = $bar = $baz = 42;

to work. The assignments are evaluated/executed right -> left, and each of the variables ends up having a value of 42.

This:

if ($city->visible = 0) {}

is equivalent to:

$city->visible = 0;
if( $city->visible ) {}

which is equivalent to:

if( 0 ) {}

which, of course, is equivalent to:

if ( false ) {
  // code that will never, under any circumstances, run. ever.
}

if ($city->visible == 0) { }

notice the == for comparison :?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top