开发者

Problems determing if value is a number

I am doing this check on a variable:

if (empty($num) || !isset ($num) || !is_nu开发者_运维百科meric ($num))
{
    $population = -1;
}
else
{
    $population = $num;
}

And what I was hoping for is that if num is null or not a number or doesn't exist, to make $population = -1 and in all other cases to give $population the value of $num

But that is not happening for me. Any ideas why this isn't working the way I thought it would?


Is this possibly an issue with scoping?

<?php
$num=23;
tryStuff();

function tryStuff(){

    global $num; //if this line is commented out, then -1 is printed. 
    if (empty($num) || !isset ($num) || !is_numeric ($num))
    {
        $population = -1;
    }
    else
    {
        $population = $num;
    }
    echo "$population<br>";
}
?>


is_numeric should work good by itself. If instead of $num the value was a super global, using isset would be a good idea to avoid warnings:

$population = is_numeric ($num) ? $num : -1;
// or
$population = isset($_GET['num']) && is_numeric($_GET['num']) ? $num : -1;


post an example of $num

using regex:

$population  = preg_match("/^\d+$/", $num) ? $num : -1; 


I'm going to go out on a limb here and say that you're inputting the number 0 and getting unexpected results, because empty(0) is true.

I think if you change your code to:

if (!isset ($num) || !is_numeric ($num))
{
    $population = -1;
}
else
{
    $population = $num;
}

You will get the desired results.

EDIT Possibly you are looking for an Integer or a Float in which case you should replace is_numeric with is_int or is_float respectively.


Why not flip it around and go with a positive as a primary check?

$population = (isset($num) && is_numeric($num)) ? $num : -1;

I've never had fun with negative's and "or" statements :)


What happens if you var_dump($num);?

Personally, my guess is that PHP is interpreting something input as a number, when you are expecting it to be a string. Such examples might include things which might accidentally convert, like '0xFF' (a string of the Hex for 255).

Clearly the issue is not about isset, because if it were, you would have caught it, and you said to evolve that this happens even without empty. This means that something which you are expecting to be is_numeric($num) === FALSE can be evaluated as TRUE.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜