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?
I've tried this code:
var_dump(in_array('14',$categoriesId));exit;
but it returns false
, and I do not know why.
Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
The 'rsort' function can be used to check if an array is multidimensional or not. It takes one parameter, i.e the array that needs to be checked and returns yes or no depending on the nature of the array.
Introduction to PHP multidimensional array A multidimensional array is an array that has more than one dimension. For example, a two-dimensional array is an array of arrays. It is like a table of rows and columns. In PHP, an element in an array can be another array.
I wonder why you don't need a for
. Well a quickest way would be to serialize
your array and do a 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.
If you need to find a specific value in an array. You have to loop it.
Do this :
var_dump(in_array("14",array_map('current',$categoriesId))); //returns true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With