php get value of array by unknown index in one statement

huangapple go评论68阅读模式
英文:

php get value of array by unknown index in one statement

问题

如果一个人不确定一个数组索引是否存在,通常会像这样做:

if (isset($array[$key]))
    $val = $array[$key];

对于大数组,是否不进行两次查找更快?

如果是的话,如何一次完成这个查找?

英文:

if one is uncertain whether an array index exists, he normally does something like

if (isset($array[$key]))
    $val = $array[$key];

for large arrays, is it faster to not do this look up two times?

If yes, how would one go about doing this in one look up?

答案1

得分: 1

你可以使用null合并运算符

$val = $array[$key] ?? null;

这等同于:

$val = isset($array[$key]) ? $array['key'] : null;

唯一的小差别是,$val 无论如何都会被定义为 null,而在你原始的代码中,如果没有 else,它将保持未定义。

我不能确定它是否执行更快,但它绝对更方便/更清晰(因为你在语句内部不需要两次编写相同的 $array[$key] 部分)。

演示:https://3v4l.org/mtG7S

英文:

You may use the null-coalescing operator:

$val = $array[$key] ?? null;

which is equivalent to:

$val = isset($array[$key]) ? $array['key'] : null;

The only minor difference is that $val gets defined no matter what (to null), where in your original code it would stay undefined if you don't have an else.

I can't say for sure that it executes faster, but it's definitely handier/cleaner to write/maintain (since you don't write the same $array[$key] part twice within the statement).

Demo: https://3v4l.org/mtG7S

huangapple
  • 本文由 发表于 2020年1月3日 17:33:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定