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.

7
  • No. Confirm the existence of multiple values inside an array Commented Dec 1, 2013 at 22:25
  • @undefined You are wrong. I check that link before even asking this. It is two entirely different question. Commented Dec 1, 2013 at 22:26
  • What was the problem with array_intersect() ? Commented Dec 1, 2013 at 22:31
  • Look at stackoverflow.com/questions/7542694/in-array-multiple-values. It looks like your question has already been asked. Commented Dec 1, 2013 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 Commented Dec 1, 2013 at 22:39

2 Answers 2

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
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1
$c = array($a, $b);
if (count(array_intersect($c, $colors)) === count($c)) {
     // ...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.