<span><span><span class="hljs-meta"><?php</span></span><span>
</span><span><span class="hljs-comment">// This article is written in PHP to explore whether is_integer and in_array can be used to determine if an array contains an integer value.</span></span><span>
<p></span>// ----------------------------------------------<span></p>
<p><span class="hljs-comment">/**</p>
<ul data-is-last-node="" data-is-only-node="">
<li>
<p>Title: Can is_integer and in_array Determine Whether an Array Contains an Integer Value?</p>
</li>
<li></li>
<li>
<p>In daily development, we often need to check if an array contains a certain integer value. At this point, <code>in_array
is_integer(5); // true
is_integer("5"); // false
is_integer(5.0); // false
Therefore, is_integer itself is not used to determine whether a value exists in an array, but rather to check types.
in_array(mixed $needle, array $haystack, bool $strict = false): bool checks whether a certain value exists in an array.
When the third parameter $strict is false (default), non-strict comparison is used, allowing type conversion.
When $strict is true, both type and value must match exactly.
Example:
$arr = [1, "2", 3];
in_array(2, $arr); // true (because "2" == 2)
in_array(2, $arr, true); // false (because 2 !== "2")
in_array(1, $arr, true); // true (because 1 === 1)
Thus, in_array can effectively check whether a value exists in an array, but whether it considers type depends on the $strict parameter.
If your requirement is to determine whether an array “contains an integer type value,” not just a value that “can be converted into an integer,” then note two points:
Use in_array($value, $array, true) to ensure the type is integer.
If you need to check whether an array “contains at least one integer type value,” you can combine is_integer with iteration.
Example: Checking if an array contains at least one integer type value
$arr = [1, "2", 3.0, true];
$hasInt = false;
foreach ($arr as $item) {
if (is_integer($item)) {
$hasInt = true;
break;
}
}
var_dump($hasInt); // true, because 1 is an integer type
is_integer is used to check whether a variable is of integer type, and cannot directly determine whether an array contains a specific value.
in_array can be used to check if an array contains a certain value, but if $strict is not set to true, automatic type conversion may occur, leading to inaccurate results.
To determine whether an array contains an integer type value, use is_integer combined with iteration.
Best Practice:
If you specifically want to check “whether the array contains a value equal to a certain integer and of type int,” you should use:
in_array(5, $array, true);
If you want to check “whether the array contains any integer type values,” you can use:
array_filter($array, 'is_int');
Or:
$hasInt = (bool) array_filter($array, 'is_int');
This ensures that both the value and type are checked accurately.
*/