Aryan Firouzian
Aryan Firouzian

Reputation: 2016

function to check if the value is int or float but not string in PHP

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){}

Upvotes: 1

Views: 1165

Answers (2)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

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?

Upvotes: 2

Aryan Firouzian
Aryan Firouzian

Reputation: 2016

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

this is what I was looking for

Upvotes: 1

Related Questions