2

The function below checks if a string is an integer meaning it should only contain digits. But it does not check if number is negative (negative numbers should return true as well since they are integers).

function validateInteger($value)
{
   //need is_numeric to avoid $value = true returns true with preg_match
   return is_numeric($value) && preg_match('/^\d+$/', $value);
}

I ran tests and got results:

'12.5'      => FALSE 
12.5        => FALSE 
'a125'      => FALSE 
'125a'      => FALSE 
'1a2.5'     => FALSE 
125         => TRUE 
'abc'       => FALSE 
false       => FALSE 
true        => FALSE 
'false'     => FALSE 
'true'      => FALSE 
null        => FALSE 
'null'      => FALSE 
'1231'      => TRUE 
-1231       => FALSE (SHOULD RETURN TRUE)
'-1231'     => FALSE (SHOULD RETURN TRUE)

I dont want to use itnval() < 0. I would prefer regular expression to check for negative numbers as well.

Thanks

EDIT:

I also have a function validateFloat that returns true if a given number is floating number meaning it can contain only digits and a dot. I need to apply same logic to this as well so that it returns true for negative floating numbers

2 Answers 2

4

is_int isn't good enough for you?

filter_var($input, FILTER_VALIDATE_INT) should have the same effect but also work on strings.

Sign up to request clarification or add additional context in comments.

5 Comments

but that returns false if value is a string but contains all digits. In my case '125' and '-1231' would return false
filter_var($input, FILTER_VALIDATE_INT) returns true if the $input = true. it should be false in that case
@GGio Try adding the option FILTER_NULL_ON_FAILURE
@GGio actually it seems like it will get cast to an int, so I think you just need to do an explicit check $input !== true && filter_var(...
filter_var( '-010', FILTER_VALIDATE_INT ) leads to a false negative, while (int)'-010' returns -10.
1

just use is_numeric(abs($val))

2 Comments

@GGio well then is_numeric($val) && is_numeric(abs($val))
My DownVote: is_numeric( abs( '125a' ) ) leads to a false positive.

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.