What's the correct way to test if a variable i

2020-02-14 04:02发布

问题:

When I fetch data from a database, the result is a string even if it has an number value. Here's what I mean:

// An integer
$int=10;
if(is_int($int)) // Returns true
...

// A string
$int='10';
if(is_int($int)) // Returns false
...

I want both of these to return true.

回答1:

Use is_numeric() if you want it to accept floating point values, and ctype_digit() for integers only.



回答2:

You're looking for is_numeric().

http://php.net/is_numeric



回答3:

You can not enclose a variable with quote (single or double quote),
anything enclosed by quote will be treated as string

see :- http://php.net/manual/en/language.types.string.php

Everything return by database (assume is mysql) is always STRING,
for your case, it will be a NUMERIC STRING
function is_numeric (like the rest has mentioned) is the right way to go

is_numeric — Finds whether a variable is a number or a numeric string



回答4:

I little hack-ish, but may be a more forceful way to check if the value "matches an integer's pattern". By that I mean it may /may not be cast explicitly to an integer, but it has all the makings of one.

function isInt($i){
  return (is_numeric($i)  // number, but not necessarily an integer
       && (int)$i == $i); // when cast it's still the same "number"
}

Example (Try your own inputs and see how it stands up)



回答5:

Cast your variable to the type you want.

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

Code:

<?

header( 'content-type: text/plain' );
$var = '10.1';

var_dump( (int)$var );
var_dump( (bool)$var );
var_dump( (float)$var );
var_dump( (string)$var );
var_dump( (array)$var );
var_dump( (object)$var );
var_dump( (unset)$var );

Output:

int(10)
bool(true)
float(10.1)
string(4) "10.1"
array(1) {
  [0]=>
  string(4) "10.1"
}
object(stdClass)#1 (1) {
  ["scalar"]=>
  string(4) "10.1"
}
NULL


回答6:

function is_number($s){
    return in_array(str_replace(str_split('0123456789'), '', $s), array(',','.',''));
}


标签: php integer