Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check value of two-dimensional array in php

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.

like image 881
trai bui Avatar asked Jan 23 '14 07:01

trai bui


People also ask

How do you check if a value exists in a multidimensional array?

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.

How do you check if a value exists in an array PHP?

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.

How check multidimensional array is empty or not in PHP?

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.

What is a 2 dimensional array PHP?

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.


2 Answers

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.

like image 66
Shankar Narayana Damodaran Avatar answered Oct 26 '22 19:10

Shankar Narayana Damodaran


Do this :

var_dump(in_array("14",array_map('current',$categoriesId))); //returns true
like image 28
Alireza Fallah Avatar answered Oct 26 '22 19:10

Alireza Fallah