subhra subhra - 27 days ago 6
PHP Question

How to search if the key value in an array exists in another array, using PHP?

I need a help. I have two arrays. I need to check if the values in first array are present in second or not. The arrays are as:

$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
$childata=array(array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123));


Here, I need to check if each value from first array is present inside second array or not. If yes, then should return
true
else
false
at each time.

Answer

Here you go, you can use the in_array() for PHP.

$maindata=array( array('id'=>3),array('id'=>7),array('id'=>9) );
$childata=array( array('id'=>7),array('id'=>11),array('id'=>3),array('id'=>123) );

foreach( $maindata as $key => $value )
{
  if( in_array( $value, $childata ) )
  {
    echo true;
  }
  else
  {
    echo false;
  }
}

You could also remove the whole if else and replace with a single line.

echo ( in_array( $value, $childata ) ? true : false );

Reference - http://php.net/manual/en/function.in-array.php https://code.tutsplus.com/tutorials/the-ternary-operator-in-php--cms-24010