0

How can a PHP script check if a value is in an array? I want it to check if a password input is equal to those in an array.

e.g. if $input == "pass1" or "pass2" or "pass3"

0

5 Answers 5

3

from php manual:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) Searches haystack for needle using loose comparison unless strict is set.

if(in_array($input, $somearray)){ .. }
Sign up to request clarification or add additional context in comments.

Comments

1

The PHP function for checking if a variable is in an array is in_array.

Like this:

if (in_array($input, array("pass1", "pass2", "pass3")) {
 // do something
}

Comments

0

Pretty much copying what Marc B stated in his comment, the example code is

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>

And in this example the second if would fail because "mac" is not contained in the array.

Comments

0

There's a couple methods. in_array is one, and foreach is another. I don't know which is faster, but here's how you'd do it with foreach:

foreach ($array as $a) {
 if ($a == "correct password") {
  //do something
 }
}

1 Comment

Bet on in_array. Not sure why you would use foreach here.
0

Here's another way,

if(count(array_intersect(array($input), array("pass1", "pass2", "pass3"))) > 0){
     //do stuff
} 

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.