PHP check if object can be converted to integer? PHP check if object can be converted to integer? php php

PHP check if object can be converted to integer?


Use is_numeric.

<?php$tests = array(    "42",     1337,     "1e4",     "not numeric",     array(),     9.1);foreach ($tests as $element) {    if (is_numeric($element)) {        echo "'{$element}' is numeric", PHP_EOL;    } else {        echo "'{$element}' is NOT numeric", PHP_EOL;    }}?>'42' is numeric'1337' is numeric'1e4' is numeric'not numeric' is NOT numeric'Array' is NOT numeric'9.1' is numeric

(From the page)


Integer (not just numeric) test: http://codepad.org/3E8IYHKY

function to_int_or_null( $v ){  if( is_int(     $v ))  return $v;   if( is_float(   $v ))  return $v === (float)(int)$v  ?  (int)$v  :  null;  if( is_numeric( $v ))  return to_int_or_null( +$v );  return null;}

Results:

int(1)                                  int(1)float(1)                                int(1)float(-0)                               int(0)string(2) "-1"                          int(-1)string(2) "+1"                          int(1)string(1) "1"                           int(1)string(2) " 1"                          int(1)string(2) "01"                          int(1)string(3) " 01"                         int(1)string(4) " -01"                        int(-1)string(3) "1e0"                         int(1)string(4) "1.00"                        int(1)string(18) "1.0000000000000001"         int(1)string(18) "0.0000000000000001"         NULLstring(17) "1.000000000000001"          NULLstring(4) "1.11"                        NULLstring(4) "1e40"                        NULLstring(6) "1e9999"                      NULLfloat(1.1100000000000000977)            NULLfloat(1.0000000000000000304E+40)        NULLfloat(INF)                              NULLstring(4) "0xFF"                        NULL or int(255) !!!string(6) "0b1111"                      NULLstring(5) "123  "                       NULLstring(0) ""                            NULLstring(2) "  "                          NULLstring(6) "123foo"                      NULLstring(6) "foo456"                      NULLstring(3) "foo"                         NULLbool(true)                              NULLbool(false)                             NULLNULL                                    NULLarray(0) {}                             NULLobject(stdClass)#7 (0) {}               NULL

Old, buggy answerhttp://codepad.org/LoqfAgNl
Fails with integer-valued float type: (double)123

function is_integerable( $v ){  return is_numeric($v) && +$v === (int)(+$v);}


See PHP's ctype_digit().

This function evaluates a string to see if all character are numeric. Thus "1.1" will not return true because "." is not numeric, but "11" will. Also note this works for strings only, so numbers without the surrounding quotation marks will also not work.