1

I have an array

array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');

And I don't want to print this array if there are only apples and oranges in it. How do I do that?

mjk
  • 2,443
  • 4
  • 33
  • 33
Itsmeromka
  • 3,621
  • 9
  • 46
  • 79

5 Answers5

4

You can take a look at this example here:

$haystack = array(...);

$target = array('foo', 'bar');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}
Community
  • 1
  • 1
Nikola
  • 14,888
  • 21
  • 101
  • 165
2

Take out the apples and oranges and see if there is anything left.

$arr = array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');
$arrDiff = array_diff($arr, array('apples', 'oranges')); //take out the apples and oranges

if(!empty($arrDiff)) //there's something other than apples and oranges in the array
    print_r($arr);
Matt K
  • 6,620
  • 3
  • 38
  • 60
1
if (in_array('apples', $array) && in_array('oranges', $array) && count($array) == 2)
{
    // Don't print array
}
imkingdavid
  • 1,411
  • 13
  • 26
0

If you know in advance the number of elements to go into the array, then you can do:

<?php
$expectedCount = 5; //in this example, we are looking for five elements in our array
if(count($array) == $expectedCount)
{
    var_dump($array);
}
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129
0

first specify the minimum amount of element the array must have for example in this case its 5 then use function count() whos reference can be found in http://php.net/manual/en/function.count.php

if(count(array) >= 5)

{

  //perform action 

}

Sagar Kadam
  • 487
  • 1
  • 3
  • 10