英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论