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,395
  • 4
  • 32
  • 33
MyMomSaysIamSpecial
  • 3,422
  • 9
  • 43
  • 75

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,548
  • 19
  • 99
  • 163
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,503
  • 3
  • 39
  • 57
1
if (in_array('apples', $array) && in_array('oranges', $array) && count($array) == 2)
{
    // Don't print array
}
imkingdavid
  • 1,402
  • 13
  • 25
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,376
  • 11
  • 66
  • 125
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