1

Is there any build-in function to check the value is number, in any integral type, like int, float but not string. is_numeric return true for "2". should I check it by both is_int and is_float?

The function that I want should return "invalid value" when $a and $b are not number:

function myFunction($a, $b, $sign){}
8
  • 6
    $number = is_int($value) || is_float($value) Commented Jul 30, 2017 at 22:11
  • 1
    Thanks, but is there any other number type in PHP? like double or decimal? Commented Jul 30, 2017 at 22:15
  • 1
    Why are you asking me? Read the manual: php.net/manual/en/language.types.php Commented Jul 30, 2017 at 22:16
  • 1
    gettype( $var ) returns double for floats, if I recall correctly. Commented Jul 30, 2017 at 22:20
  • 2
    is_numeric($value) && !is_string($value) is an alternative to the first comment. Commented Jul 30, 2017 at 22:28

2 Answers 2

2

This isn't an answer per se, but this is too much to put in a comment:

function isFloatOrInt($var)
{
    $type = gettype($var);

    switch ($type) {
        case 'integer':
        case 'double':
            return true;
        case 'string':
            //check for number embedded in strings "1" "0.12"
            return preg_match('/^[0-9]+(?:\.[0-9]+)?$/', $var);
        default:
            return false;
}

Preg match can be useful here if you consider the string version of a number to still be a number.

You say

But not string

But does that mean this 'string' or this '10' instead of 10 for example, ie. a string that is also a number?

There is probably many ways to do this, but there are some edge cases so it's largely depends on your needs. For example is an octet a number to you 0777 or and exponent 12e4 or even Hexadecimal 0xf4c3b00c?

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

3 Comments

This is definitely not the simplest solution.
No but under certain situations is_numeric can return a number when you don't want it to, such as '102e8' which it may see as an exponent.
It depends, it's not ok for say a phone number, or a zip code. I've seen excel transform phone numbers into exponents in csv files for example.
1

is_numeric($value) && !is_string($value)

this is what I was looking for

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.