如何检查是否存在多个数组键 [英] How to check if multiple array keys exists

查看:72
本文介绍了如何检查是否存在多个数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有各种将包含的数组

story & message

或者只是

story

我将如何查看数组是否同时包含故事和消息? array_key_exists()仅在数组中查找该单个键.

How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

如果您只有2个要检查的键(就像在原始问题中一样),只需调用

If you only have 2 keys to check (like in the original question), it's probably easy enough to just call array_key_exists() twice to check if the keys exists.

if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
    // Both keys exist.
}

但是,这显然不能很好地扩展到许多键.在这种情况下,自定义功能会有所帮助.

However this obviously doesn't scale up well to many keys. In that situation a custom function would help.

function array_keys_exists(array $keys, array $arr) {
   return !array_diff_key(array_flip($keys), $arr);
}

这篇关于如何检查是否存在多个数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆