user5443928
user5443928

Reputation:

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.

Upvotes: 1

Views: 2936

Answers (5)

Blinkydamo
Blinkydamo

Reputation: 1584

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

Upvotes: 3

d.coder
d.coder

Reputation: 2038

Following code will return true only if all elements of main array exists in second array, false otherwise:

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

$match = 0;
foreach( $maindata as $key => $value ) {
  if( in_array( $value, $childata ) ) {
    $match++;
  }
}
if($match == count($maindata)){
    // return true;
} else {
    // return false;
}

Upvotes: 1

jitendrapurohit
jitendrapurohit

Reputation: 9675

Use array_column and array_intersect.

$first = array_column($maindata, 'id');
$second = array_column($childata, 'id');

//If intersect done, means column are common
if (count(array_intersect($first, $second)) > 0) {
  echo "Value present from maindata in childata array.";
}
else {
  echo "No values are common.";
}

Upvotes: 0

user3146115
user3146115

Reputation:

Use array_intersect

if(!empty(array_intersect($childata, $maindata)))
{
   //do something
}

or

$result  = count(array_intersect($childata, $maindata)) == count($childata);

Upvotes: 0

Peter
Peter

Reputation: 9123

To check if an array contains a value:

if (in_array($value, $array)) {
    // ... logic here
}

To check if an array contains a certain key:

if (array_key_exists($key, $array)) {
    // ... logic here
}

Resources

Upvotes: 1

Related Questions