How to use in_array in multidimensional array in PHP ?

We use in_array() to check whether a value exists in an array like below,

$a = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $a))
{
echo "Got Irix";
}

but what about an multidimensional array.In this tutorial we will discuss how to use in_array in multidimensional array in PHP. Suppose you have an array like below

$myArray = Array (
          [0] => Array (
          [id] => 1
          [pid] => 120
          [uuid] => 1
       )
     [1] => Array (
          [id] => 2
          [pid] => 132
          [uuid] => 1
      )
     [2] => Array (
          [id] => 5
          [pid] => 121
          [uuid] => 1
          )
 );

Suppose you do not want to show the value [pid] => 121 . Use the below function

function inMyArray($array, $search)
{
   foreach($array as $value)
{
if(is_array($value))
{
  if(inMyArray($value, $search))
  {
     return(TRUE);
   }
}
elseif($value == $search)
  {
     return(TRUE);
  }
}
return(FALSE);
}

Now use the function like this

$id = 121;

if(inMyArray($myArray, $id))
{

   echo "Value 121 found in array";
}else{

echo "Other value";

}

Hope this small tutorial How to use in_array in multidimensional array in PHP will help you guys.

  • Harry Sainipur

    asdghaj