2

Whats the easiest and quickest way to loop through an array of numbers and find out if $val is in there?

Say my array is $numbers(3,5,78,35,78) and my $val=5, it would return true.

3
  • Both goleztrol and clive have the right answers. in_array is a simple true/false, while array_search returns the corresponding key if the value is found. Whichever of the two you use depends on what you need to do. Commented Oct 31, 2011 at 20:54
  • @MarcB In this case in_array is the best. I thought of it only after posting array_search, but since Clive suggested in_array as well by that time, I removed my answer. Commented Oct 31, 2011 at 20:57
  • @Golez: in_array() is basically array_search(..) !== FALSE. Commented Oct 31, 2011 at 20:59

2 Answers 2

10

Maybe in_array()?

if (in_array($val, $numbers)) {
  // Do something
}

No looping required

Sign up to request clarification or add additional context in comments.

2 Comments

What would be the correct syntax for: if (($key == "red") && (in_array($val, $numbers)))
Do you mean if "red" is a key of the array? If so just extend it with array_keys: if (in_array("red", array_keys($arr))) { ...
1

If you don't care about the position of your number, you could use in_array()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.