0
$a = 'red';
$b = 'blue'; 
$colors = ['red', 'green', 'blue', 'black'];

I am trying to check if both $a, and $b are present in $colors If yes, return true else return false

I could obviously do

if(in_array($a, $colors) && in_array($b, $colors)){
  //true
}

But, I am hoping for an array function that can do both in on call, or any method simpler than that. I tried with array_intersect() to no avail.

samayo
  • 16,163
  • 12
  • 91
  • 106
  • No. *Confirm the existence of multiple values inside an array* – samayo Dec 01 '13 at 22:25
  • @undefined You are wrong. I check that link before even asking this. It is two entirely different question. – samayo Dec 01 '13 at 22:26
  • What was the problem with `array_intersect()` ? – bagonyi Dec 01 '13 at 22:31
  • Look at http://stackoverflow.com/questions/7542694/in-array-multiple-values. It looks like your question has already been asked. – sheng Dec 01 '13 at 22:35
  • @ShengSlogar Yes, it does seem to have been answered. Not sure if all the answers I have seen so far provider simpler solutions to the example I have posted so-far – samayo Dec 01 '13 at 22:39
  • Look at the accepted answer to the link I gave you. It uses ``array_intersect`` and it is the easiest way I've found as it dosen't use && for each wanted value. – sheng Dec 01 '13 at 22:43
  • Thanks but I have went with && to get the job done, as it calls less functions resulting to less overhead of the script – samayo Dec 03 '13 at 18:53

2 Answers2

3

array_intersect() should have worked, but you may also try array_diff(). If the result is an empty array, then every element of the first array was found in the second array.

<?php
if(count(array_diff(array($a, $b), $colors)) == 0)
{
// Both found
}
?>
mcserep
  • 3,231
  • 21
  • 36
1
$c = array($a, $b);
if (count(array_intersect($c, $colors)) === count($c)) {
     // ...
}
Ram
  • 143,282
  • 16
  • 168
  • 197