UserKa
UserKa

Reputation: 353

How exactly php checks boolean values in parentheses

I am trying to understand how php hadles this examples.

(\Auth::check() || \Auth::user()->isAdmin())
(\Auth::check() && \Auth::user()->isAdmin())

\Auth::check() gives only false or true while \Auth::user()->isAdmin() can give true, false or user object can be null and isAdmin() function gives error.

When I run (\Auth::check() || \Auth::user()->isAdmin()) it gives me error because \Auth::check() is false and \Auth::user() is null, but when I replace || with && it's ok although user object still null and isAdmin function must give error.

P.S. Sorry for the vague question (I don't know what to do if there is need to change question but there are answers already) Some clarification: I suspect that when there is && and php checks first argument and it is false then php never checks other. Am I right? I think so because in my case (false && null->method) give just false but (false || null->method) gives error because of null->method

Upvotes: 2

Views: 409

Answers (4)

UserKa
UserKa

Reputation: 353

I just tested in practice and figure it out:

$a = null
dd(false && $a->func());

and it return false but then it tried dd(false || $a->func()); and this return error: Undefined variable: null

So in case && if first argument is false php don't checks other arguments even it is not boolean (in my case $a->func())

Upvotes: -1

slevy1
slevy1

Reputation: 3820

One more thing. true && null will result in null evaluating in a boolean context as false with the expression evaluating overall as false; see: first comparison table here.

Example:

<?php

var_dump( true && null);

live code.

Logical && is a binary operator and when an expression using this operator evaluates only one of two possible results are possible, i.e true or false.

Upvotes: 0

aknosis
aknosis

Reputation: 4328

You can read up on logical operators here: http://php.net/manual/en/language.operators.logical.php

|| is OR operator, if the left OR right side are true then the condition will pass. The left side of the operator is tested first then the right side

&& is AND operator, if the left AND right side are true the the condition will pass. The left side is run first then the right side. If the left side is false, the right side is never evaluated.

Upvotes: 3

NorteAmaru
NorteAmaru

Reputation: 11

I suspect that when there is && php check only first argument and drop other. Am I right?

-No. $a && $b TRUE if both $a and $b are TRUE.

Upvotes: 0

Related Questions