PHP is_numeric - false when Exponent in string -


<?php  $val = '245e1';  var_dump($val); // return string(5) "245e1"  $n = is_numeric($val); var_dump($n); // return bool(true) 

problem: is_numeric return true

questions:

  1. how treat $val string, not number?

  2. how disable exponent interpretation?

from manual on is_numeric(), you'll notice there plenty of characters can go in:

numeric strings consist of optional sign, number of digits, optional decimal part , optional exponential part. +0123.45e6 valid numeric value. hexadecimal (e.g. 0xf4c3b00c), binary (e.g. 0b10100111001), octal (e.g. 0777) notation allowed without sign, decimal , exponential part.

if wish check if variable type integer, can use is_int(), , floats, can use is_float(). note, though, e.g. is_int(), variable must of type integer, not numeric string. use ctype_digit() this, variable type have string; or specifically, not integer matches ascii character's ord().

it may easiest use if (preg_match('#^\d+(\.\d+)?$#', $str)) validate variable of which-ever type having digits. (remove expression in brackets pattern if optional decimals not welcome.)

the other option ctype_digit((string) $str) , casting variable string type avoid ascii mapping clash integer types. not return true if had decimal points.

100000 loops of ctype_digit: 0.0340 sec. 100000 loops of preg_match: 0.1120 sec. use ctype_digit if want digits , intend a lot. otherwise; whatever fits style.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

node.js - Using Node without global install -

php - CakePHP HttpSockets send array of paramms -