Search code examples
phpnullis-empty

What is the safest php method to check that a string is a number?


I checked various method (is_numeric, isset), but I'm not sure built methods are safe in any case.

I need it to work even if the variable to check is:

  • an empty string
  • null/undefined or whatever invalid state possible

Solution

  • I hope this covers all your cases. is_numeric seems safe enough.

    $values = [
        0,
        -3232323,
        423432094823904832948234574072357589345789345789345791305432794827342365786345693453417846393,
        123232e43,
        '-1232132132',
        '023',
        'abcdefaf',
        '0xdeadbeef',
        '',
        null
    ];
    
    
    foreach ($values as $val) {
        echo var_export($val, true);
        if (is_numeric($val))
            echo " is numeric\n";
        else
            echo " is NOT numeric\n";
    }
    

    Output:

    0 is numeric
    -3232323 is numeric
    4.2343209482390483E+92 is numeric
    1.23232E+48 is numeric
    '-1232132132' is numeric
    '023' is numeric
    'abcdefaf' is NOT numeric
    '0xdeadbeef' is NOT numeric
    '' is NOT numeric
    NULL is NOT numeric