Blease
Blease

Reputation: 1420

PHP Check Array with Post

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"

Upvotes: 0

Views: 307

Answers (5)

Jay Bhatt
Jay Bhatt

Reputation: 5651

Here's another way,

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

Upvotes: 0

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41935

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
}

Upvotes: 1

Norse
Norse

Reputation: 5757

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
 }
}

Upvotes: 0

Zanrok
Zanrok

Reputation: 297

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.

Upvotes: 0

Elen
Elen

Reputation: 2343

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)){ .. }

Upvotes: 3

Related Questions