php - 查找数组是否包含元素 [英] php - find if an array contains an element

查看:29
本文介绍了php - 查找数组是否包含元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只有 id 列表的数组,如下所示:

I have an array with just a list of ids, like so:

$my_array = array(
 12, 17, 99, 23
);

现在我知道我可能会这样做:

Now I know I could probably do something like:

function in_array($haystack = array(), $needle = NULL)
{
 foreach($haystack as $id)
 {
  if ($id == $needle)
  {return TRUE;}
  else
  {return FALSE;}
 }
}

但似乎已经构建了一个函数.我可以用什么?

but it seems like there's probably already a function built. What could I use?

推荐答案

不需要创建一个,它已经存在,并且与您正在使用的名称相同:in_array 也是.

No need to create one, it is already there co-incidentally with the same name you are using: in_array too.

示例:

if (in_array('foo', $array)){
  // foo is in the array
}

这篇关于php - 查找数组是否包含元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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