I have 2 arrays as given below. I want to check if all items of first array $arrayA
are available in $arrayB
against key fruit
. How I can do that?
<?php
$arrayA = ['apple', 'guava'];
$arrayB = [
['fruit' => 'apple','vegetables' => 'potato'],
['fruit' => 'guava','vegetables' => 'onion']
];
$containsSearch = count(array_intersect($arrayA, $arrayB)) == count($arrayA);
var_dump($containsSearch);
Above code returns error:
PHP Notice: Array to string conversion in /var/www/html/test/b.php on line 8
You probably want to use array_column()
as you only want to use the fruit
key. This should then be:
// array_column($arrayB, 'fruit') instead of $arrayB
$containsSearch = count(array_intersect($arrayA, array_column($arrayB, 'fruit'))) == count($arrayA);
$diff = array_diff($arrayA, array_column($arrayB,'fruit'));
if(count($diff) == 0){
echo 'all items of first array $arrayA are available in $arrayB against key fruit';
} else print_r($diff);
array_column()
is a necessary step to isolate the fruit
elements. count()
calls are not necessary because the filtered $arrayA
will be ordered the same as the unfiltered $arrayA
so you can check them identically.
Code: (Demo)
$arrayA = ['apple', 'guava'];
$arrayB = [
['fruit' => 'apple','vegetables' => 'potato'],
['fruit' => 'guava','vegetables' => 'onion']
];
var_export(array_intersect($arrayA, array_column($arrayB, 'fruit')) === $arrayA);
Output:
true