'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!

php


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sébastien VINCENT