I have an array like this:
我有一个像这样的数组:
array(2) {
[0]=> array(1) { ["cate_id"]=> string(2) "14" }
[1]=> array(1) { ["cate_id"]=> string(2) "15" }
}
How can I check if the value 14 exists in the array without using a for loop?
如何在不使用for循环的情况下检查数组中是否存在值14?
I've tried this code:
我试过这段代码:
var_dump(in_array('14',$categoriesId));exit;
but it returns false
, and I do not know why.
但它返回false,我不知道为什么。
2 个解决方案
#1
6
I wonder why you don't need a for
. Well a quickest way would be to serialize
your array and do a strpos
.
我想知道为什么你不需要一个。最快的方法是序列化你的数组并做一个strpos。
$yourarray = array('200','3012','14');
if(strpos(serialize($yourarray),14)!==false)
{
echo "value exists";
}
Warning :
Without using looping structures you cannot guarantee the value existence inside an array. Even an in_array
uses internal looping structures. So as the comments indicate you will get a false positive if there is 1414
inside the $yourarray
variable. That's why I made it a point in the first place.
警告:如果不使用循环结构,则无法保证数组中存在值。即使是in_array也使用内部循环结构。因此,如果评论表明如果$ yourarray变量中有1414,则会出现误报。这就是为什么我首先要说明这一点。
If you need to find a specific value in an array. You have to loop it.
如果需要在数组中查找特定值。你必须循环它。
#2
2
Do this :
做这个 :
var_dump(in_array("14",array_map('current',$categoriesId))); //returns true
#1
6
I wonder why you don't need a for
. Well a quickest way would be to serialize
your array and do a strpos
.
我想知道为什么你不需要一个。最快的方法是序列化你的数组并做一个strpos。
$yourarray = array('200','3012','14');
if(strpos(serialize($yourarray),14)!==false)
{
echo "value exists";
}
Warning :
Without using looping structures you cannot guarantee the value existence inside an array. Even an in_array
uses internal looping structures. So as the comments indicate you will get a false positive if there is 1414
inside the $yourarray
variable. That's why I made it a point in the first place.
警告:如果不使用循环结构,则无法保证数组中存在值。即使是in_array也使用内部循环结构。因此,如果评论表明如果$ yourarray变量中有1414,则会出现误报。这就是为什么我首先要说明这一点。
If you need to find a specific value in an array. You have to loop it.
如果需要在数组中查找特定值。你必须循环它。
#2
2
Do this :
做这个 :
var_dump(in_array("14",array_map('current',$categoriesId))); //returns true