I've noticed a strange thing about PHP's in_array
function. For some reason, it will only check if the first character(s) of the needle match with any of the values of the haystack - as opposed to if the whole needle is in the haystack.
For example, in a situation where $string
equals 1thisisatest
, the following script will return In array
.
$allowed = [0, 1];
if(in_array($string, $allowed)){
echo "In array";
} else {
echo "Not in array";
}
Whereas if $string
equals 2thisatest
, the script will return Not in array
.
Now either this is a bug, or a very strange feature. Wouldn't you want it to check needles against the haystack exactly as they appear?
If this is, indeed, how the function is supposed to work, how does one go about getting the intended result without iterating over every single element in the array? Seems kind of pointless.
EDIT:
Some of you are saying to use strict mode. This is all fine and dandy, until you checking against $_GET
data, which is always a string. So the following will return false
:
$value = $_GET["value"]; // this returns "1"
in_array($value, [0, 1], true)