James Corr
James Corr

Reputation: 81

PHP Shorthand Syntax to AND statements

I am trying to implement the logical connective AND, and was wondering if this shorthand notation is allowed:

$hasPermissions &= user_hasAppPermission($user_id, $permission);

Or do i have to do this:

$hasPermissions = $hasPermissions && user_hasAppPermission($user_id, $permission);

Upvotes: 0

Views: 353

Answers (3)

SteAp
SteAp

Reputation: 11999

In PHP, these logical operations are available:

AND

$val1 && $val2
$val1 and $val2

OR

$val1 || $val2
$val1 or $val2

NOT

! $val

XOR

$val1 xor $val2

Additionally, have a look at this page. The two operators && and || have a different precedence as and and or.

Thus, your second option is the way to go:

$hasPermissions = $hasPermissions && user_hasAppPermission($user_id, $permission);

BTW: I'd propose to always use === to compare for equality. === ensures that the types of its operands are identical and the values are, while == casts values.

Upvotes: 1

Mike Purcell
Mike Purcell

Reputation: 19999

I would do something like:

$hasPermissions = (($hasPermissions) && (true === user_hasAppPermission($user_id, $permission))) ? true : false;

Upvotes: 0

user142162
user142162

Reputation:

The shorthand &= is a bitwise assignment operation, which is not equivalent to your second statement. That would be the same as doing (note the single ampersand):

$hasPermissions = $hasPermissions & user_hasAppPermission($user_id, $permission);

From what I can see, your "long" statement seems fine as is.

Upvotes: 5

Related Questions