Recently I was working on a project that involved the usage of PayPal REST API SDK.
To give a little bit of background, starting in PHP 7.x (I believe 7.2), the language will throw a warning if you use sizeof on a variable that does not implement Countable. Arrays implement Countable, but obviously not primitive types, such as integer for example:
php > var_dump( sizeof( [] ) ); int(0) php > var_dump( sizeof( 1 ) ); PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable in php shell code on line 1 int(1)
So, now depending on how we use sizeof, it can trigger the warning which is a kind of a side-effect. In PayPal, before they provided a fix for it, what they did was:
if (sizeof($v) <= 0 && is_array($v))
After:
if (is_array($v) && sizeof($v) <= 0)
The only difference in the code above is the order of operations. The second code snippet won’t trigger the warning. However, for the first one, obviously if the variable $v does not implement Countable, you will get the warning.
Mathematically, the logical AND operation is commutative, i.e. a AND b = b AND a. In some cases, it can also be commutative in programming, up until the point side effects are involved.
So a AND b may not necessarily be b AND a if there are side effects involved. There’s a good reason for this “trade-off”, since side effects can be expensive so if evaluating only the first one returns false there’s no need to evaluate the rest of them to waste resources (since we know that false AND a AND ... is false). The side effect here is PHP throwing warnings to stdout on sizeof.