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?
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With