4

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.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

6 Answers6

5

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

  • Should use `is_int` for testing for integers, `ctype_digit` checks whether the string contains only numerical digits or not. – dayuloli Jun 23 '13 at 15:33
2

You're looking for is_numeric().

http://php.net/is_numeric

Xavura
  • 164
  • 2
  • 8
  • 2
    is_numeric and is_int are two different things, however. onc accepts only whole numbers, the other allows decimals, scientific notations, etc. – Brad Christie Dec 07 '11 at 03:09
1

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

ajreal
  • 46,720
  • 11
  • 89
  • 119
1

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)

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

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
Tim G
  • 1,812
  • 12
  • 25
0
function is_number($s){
    return in_array(str_replace(str_split('0123456789'), '', $s), array(',','.',''));
}