PHP Check Array with Post

Go To StackoverFlow.com

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"

2012-04-03 22:00
by Josh Luke Blease


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
}
2012-04-03 22:03
by Benjamin Crouzier


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)){ .. }
2012-04-03 22:04
by Elen


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.

2012-04-03 22:05
by Zanrok


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
 }
}
2012-04-03 22:05
by Norse
Bet on in_array. Not sure why you would use foreach here - Basti 2012-04-03 22:28


0

Here's another way,

if(count(array_intersect(array($input), array("pass1", "pass2", "pass3"))) > 0){
     //do stuff
} 
2013-12-30 16:20
by Jay Bhatt