0

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.

5
  • 10
    Those are strings not floats. $new_estimate=array(3.3,10.3,1.1,2.35); A var_dump() would show you this. Commented Dec 12, 2014 at 21:59
  • 3
    Remove the quotes 'round yer floats Commented Dec 12, 2014 at 22:00
  • 1
    Looking for FILTER_VALIDATE_FLOAT perhaps, when the sample array is meant to be form input? Commented Dec 12, 2014 at 22:02
  • you can update existing code like this if (!is_float((float) $new_estimate[$i])) Commented Dec 12, 2014 at 22:06
  • @saqibahmad If you cast to float, it's bound to be a float so testing for that will not do much... Commented Dec 12, 2014 at 22:08

2 Answers 2

2

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 );
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.