Reputation: 65
I need to validate inputs - find out, if inputs are float. According to websites, my code should work, but it doesnt.
<?php
$new_estimate=array("3.3","10.3","1.1","2.35");
$mistake="no";
for ($i=0; $i<(sizeof($new_estimate)); $i++)
{
if (!is_float($new_estimate[$i]))
{
$mistake="yes";
}
}
echo $mistake;
?>
I think all values of array are float, but browser shows "yes" - instead my expectation. I dont understand, why it doesnt work.
Upvotes: 0
Views: 197
Reputation: 12689
It is because is_float() checks if the type of a variable is float, and you are working with an array of string values. To validate inputs you can use filter_var() as in example below.
$new_estimate = array( "3.3", "10.3", "1.1", "2.35" );
$mistake = (bool) array_filter( $new_estimate, function( $item ) {
return !filter_var( $item, FILTER_VALIDATE_FLOAT );
});
Upvotes: 2
Reputation: 6404
This are strings in your array, if you'd like them to be floats remove the "
around the numbers. If you intend to check for numbers instead of the concrete type, use is_numeric
(Documentation).
$new_estimate = array(3.3, 10.3, 1.1, 2.35);
Furthermore, instead using the strings "yes"
and "no"
for $mistake
, set them true
or false
and use the variable as a boolean.
Upvotes: 1