0

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?

4

1 回答 1

1

在一个项目中,我有用户提交的 $var 的值。

这是如何运作的?用户不应该能够设置变量。他们应该能够,例如,提交最终以$_POST. 我再说一遍,他们不应该直接在你的范围内创建变量

如果这里的“用户”意味着人们编写的某种插件系统和includePHP 代码……那么您可能需要考虑定义一个比设置变量更稳定的接口。

该值可以是任何值,甚至是 NULL……</p>

如果它是通过 HTTP 提交的值,则不会。HTTP 没有null. 它要么是空字符串,要么根本不存在。

!empty($var)单独使用是危险的,因为如果$var没有预先定义,PHP 会抛出错误

那是错的。empty 专门用于测试变量是否为false而不会引发错误。如果变量不存在,则与不触发错误empty($var)相同。!$var

所以我必须isset($var) && !empty($var)检查是否$var持有非空值。

请参阅为什么同时检查 isset() 和 !empty()。(剧透:这是多余的。)

echo isset($arr['foo']);
echo array_key_exists('foo', $arr) && !is_null($arr['foo']);

它们都做同样的事情。如果值存在且其值不存在则isset返回。如果数组键存在且其值不存在,则第二行返回。一样。truenulltruenull

我有不好的经历...

您需要对此进行更详细的说明,因为isset您描述它时不应该有任何警告。

请参阅PHP 的 isset 和空的权威指南以及isset 和 array_key_exists 之间的区别

于 2018-05-25T08:28:04.170 回答