PHP : benchmarking empty() and negation (!)
When I tried to get this website working, the server running PHP5.4 threw me this error: `Can't use method return value in write context`.Then, I found this StackOverflow comment from Kornel…
He stated that:
However, the real problem you have is that you use
empty()
at all, mistakenly believing that “empty” value is any different from “false”.
Empty is just an alias for
!isset($thing) || !$thing
. When the thing you’re checking always exists, theempty()
function is nothing but a negation operator.
Here is a small benchmark I made to demonstrate it:
<?php
/*
* Testing empty() VS negation '!'
*/
// Array of value
$var = [null, true, false, 0, 1, '0', '1', ''];
foreach ($var as $v) {
debug([empty($v), !$v]);
}
/*
* Outputs
*/
//null
[
(int) 0 => true,
(int) 1 => true
]
// true
[
(int) 0 => false,
(int) 1 => false
]
// false
[
(int) 0 => true,
(int) 1 => true
]
// 0
[
(int) 0 => true,
(int) 1 => true
]
// 1
[
(int) 0 => false,
(int) 1 => false
]
// '0'
[
(int) 0 => true,
(int) 1 => true
]
// '1'
[
(int) 0 => false,
(int) 1 => false
]
// ''
[
(int) 0 => true,
(int) 1 => true
]