is_double() is a built-in function in PHP used to check if a variable is of float type. Its usage is identical to is_float(), and in fact, is_double() is just an alias for is_float().
Syntax:
is_double(mixed $var): bool
Return Value:
If $var is a float, it returns true.
Otherwise, it returns false.
You can use array_filter() together with is_double() to filter out float elements from an array. For example:
<?php
$values = [10, 3.14, 'hello', 2.718, 42, 0.99, true];
<p>$floats = array_filter($values, 'is_double');</p>
<p>print_r($floats);<br>
?><br>
Output:
Array
(
[1] => 3.14
[3] => 2.718
[5] => 0.99
)
Here, we use array_filter() to iterate through each element of the array and call is_double() on each one. The resulting array contains only float values.
If you want to apply more complex checks, for example, keeping only floats greater than 1.0, you can use an anonymous function as a callback:
<?php
$values = [0.5, 1.5, 2, '3.0', 3.14, false];
<p>$result = array_filter($values, function($val) {<br>
return is_double($val) && $val > 1.0;<br>
});</p>
<p>print_r($result);<br>
?><br>
Output:
Array
(
[1] => 1.5
[4] => 3.14
)
Sometimes, we need to iterate through an array and check the type of each element. This can be done using a foreach loop:
<?php
$data = [1.23, '2.34', 3, 4.56, null];
<p>foreach ($data as $index => $value) {<br>
if (is_double($value)) {<br>
echo "Element at index $index is a float, value: $value\n";<br>
} else {<br>
echo "Element at index $index is not a float, type: " . gettype($value) . "\n";<br>
}<br>
}<br>
?><br>
Output:
Element at index 0 is a float, value: 1.23
Element at index 1 is not a float, type: string
Element at index 2 is not a float, type: integer
Element at index 3 is a float, value: 4.56
Element at index 4 is not a float, type: NULL
Imagine you are building a simple API that accepts an array of numbers from the client and extracts only the float values for some calculations:
<?php
// Assuming data received from a POST request
$user_input = json_decode(file_get_contents('https://gitbox.net/api/input'), true);
<p>$floats = array_filter($user_input, 'is_double');</p>
<p>// Perform further calculations<br>
$total = array_sum($floats);<br>
echo "The sum of the floats is: $total";<br>
?><br>
Although is_double() is often replaced by is_float() in practice, both functions are identical in functionality, and developers can choose which one to use based on their preference. By combining array_filter(), anonymous functions, and foreach, we can flexibly filter and process float values in arrays, improving code robustness and readability.
Using is_double() allows for more precise control over data types, providing stronger type guarantees for PHP applications.