如何检查数组是否包含php中的特定值?

新手上路,请多包涵

我有一个 Array 类型的 PHP 变量,我想知道它是否包含特定值并让用户知道它在那里。这是我的数组:

 Array ( [0] => kitchen [1] => bedroom [2] => living_room [3] => dining_room)

我想做类似的事情:

 if(Array contains 'kitchen') {echo 'this array contains kitchen';}

执行上述操作的最佳方法是什么?

原文由 hairynuggets 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 367
2 个回答

使用 in_array() 功能

 $array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}

原文由 Wiseguy 发布,翻译遵循 CC BY-SA 3.0 许可协议

以下是如何执行此操作:

 <?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

确保您搜索的是 kitchen 而不是 Kitchen 。此函数区分大小写。因此,以下功能根本不起作用:

 $rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

如果您想要一种快速使此搜索 不区分大小写 的方法,请查看此回复中建议的解决方案: https ://stackoverflow.com/a/30555568/8661779

资料来源: http ://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

原文由 Pranav Rana 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题