Knowing the differences of array_key_exists()
and isset()
in PHP, I see a lot of advocates on the web suggesting for replacing array_key_exists()
with isset()
, but I am thinking is it safe to do so?
In one project, I have the value of $var submitted by users. The value can be anything, even NULL or not set at all. I want to use !empty($var)
to check if $var
holds a non-empty value, but I understand that using !empty($var)
alone is dangerous since if $var
isn't pre-defined, PHP will throw an error.
So I have isset($var) && !empty($var)
for checking whether $var
holds a non-empty value.
However, things get complicated when I have a value stored in an assoc array. Compare the followings, assuming array $arr
always exists but the key foo
may or may not exist in $arr
.
// code snipplet 1
$arr = array();
echo isset($arr['foo']);
// code snipplet 2
$arr = array();
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);
Code snipplet 2 will always work but it seems clumsy and harder to read. As for code snipplet 1, I had bad experience... I wrote something like that before in the past on a development machine. It ran fine, but when I deployed the code to the production machine, it threw errors simply because key didn't exist in array. After some debugging, I found that the PHP configs were different between the development and the production machines and their PHP versions are slightly different.
So, I am thinking is it really that safe to just replace array_key_exists()
with isset()
? If not, what can be of better alternatives of code snipplet 2?