ITChristian
ITChristian

Reputation: 11271

PHP Check if variable is contained in an array

I have a numeric variable $i. This is a while loop, and $i increments after each iteration.

How can a conditional statement be made as to not be necessary to write such a long statement if($i == 1 || $i == 2 || $i == 25 [...])?

Thanks in advance!

Upvotes: 0

Views: 86

Answers (2)

Seems a bit obvious that you should take a deeper look at the documentation of PHP. There is standards functions that can do a lot and help you save a lot of time.

You say that you've got a string but show an example with an array. Assuming you really have a string in input you may try explode() function to explode it to an array of objects.

Then having a real Array in_array() function will do the job.

$resultString = "12 13 17 26";
$resultArray = explode(" ", $resultString);
if (in_array("13", $resultArray)) {
    echo "found";
} else {
    echo "not found";
}

Upvotes: 0

Sumoanand
Sumoanand

Reputation: 8929

Use php in_array.

$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}

Upvotes: 3

Related Questions