0

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

AymDev
  • 6,626
  • 4
  • 29
  • 52
amitshree
  • 2,048
  • 2
  • 23
  • 41

3 Answers3

2

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);
AymDev
  • 6,626
  • 4
  • 29
  • 52
1

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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0
    $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);
TsV
  • 629
  • 4
  • 7