Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma Operator PHP

Both these statements are true:

$_POST['foo'] = $_POST['bar'] = 'some string';

//1. with '&&' operator
if(isset($_POST['foo']) && isset($_POST['bar'])) { 
    echo true; 
}

//2. with a comma
if(isset($_POST['foo'], $_POST['bar'])) { 
    echo true; 
}

What is the difference (if any) between them?

like image 586
Edward Avatar asked Jan 11 '23 15:01

Edward


2 Answers

There IS a difference, in practice. The meaning should be the same, however the "comma operator" version implements a "complete boolean evaluation" in this case. That is, if the first variable is not set, php won't look at the second since they're in a && relationship and the result can't be true anymore. (This is called a "short circuit" eval) In the second case, php must calculate both arguments before calling isset(...) so both values will be checked.

It's just the principle, yes, but sometimes it's very important, for example if the operands are function calls.

(Just a short reply to the commenter saying "isset does not take function calls" - it's not about isset, it's about implementing expressions in general. Stop calculating things as soon as the result is obvious, and spare yourself as many partial results as you can. Function arguments will do the opposite: they all get calculated before they get passed to the subroutine.)

like image 72
dkellner Avatar answered Jan 16 '23 20:01

dkellner


There's no difference according to the PHP documentation: isset() function. Indeed, isset can take an infinity of argument and returns true if every variable passed exists. It's similar to test if each isset() of each variable is true.

The theory should be check, but the function takes only variable in argument as said by the doc:

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

... So there's no problem about priority of the compute of arguments.

Finally, be aware that the comma here isn't an operator. The comma here is used to separated arguments of the isset function. The previous explanation doesn't work with empty() for example since the empty function only takes 1 argument.

TL;DR: isset($a, $b) == isset($a) && isset($b), but empty($a, $b) is a syntax error.

like image 26
Maxime Lorant Avatar answered Jan 16 '23 20:01

Maxime Lorant