You are right, is_numeric
works with strpos
. But this can make the code tricky, hence lowering code readability.
Have in mind that although this may seems obvious to you, you are making another programmer that reads your code think in a lot of things:
- Does the haystack contains the needle?
- Which is the position of the needle in the haystack?
- What type of value does strpos returns?
- Is the returned value of strpos a number in this case?
And PHP can be quite a tricky language by itself, take a look at this examples:
if (strpos("needle in a haystack","needle")!==false) {
echo "Needle found!<br>";
} else {
echo "nothing found<br>";
}
if (is_numeric(strpos("needle in a haystack","needle"))) {
echo "Needle found!<br>";
} else {
echo "nothing found<br>";
}
if (is_int(strpos("needle in a haystack","needle"))) {
echo "Needle found!<br>";
} else {
echo "nothing found<br>";
}
// This doesn't work since 0 == false is true
if (strpos("needle in a haystack","needle")!=false) {
echo "Needle found!<br>";
} else {
echo "nothing found<br>";
}
// But this works since "haystack" position is not 0
if (strpos("needle in a haystack","haystack")!=false) {
echo "Haystack found!<br>";
} else {
echo "nothing found<br>";
}
// This doesn't work also because "needle" is at 0, and 0 is not a truthy value
if (strpos("needle in a haystack","needle")) {
echo "Needle found!<br>";
} else {
echo "nothing found<br>";
}
// But this works again since "haystack" position is not 0, and any int that's not 0 is truthy
if (strpos("needle in a haystack","haystack")) {
echo "Haystack found!<br>";
} else {
echo "nothing found<br>";
}
Imho, the best option is using ===false
and ==!false
comparisons, like explained in the php documentation for strpos:
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
PD: For a better definition of "truthy" take a look at this post.