Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP "is_numeric" accepts "E" as a number

I noticed PHP is_numeric() accepts "E" as a number. I have a string: "88205052E00" and I want the result to be: NOT numeric.

Here is the code which I tested.

<?php

$notnumber = '88205052E00';

if(is_numeric($notnumber)) {
    echo $notnumber . ' is a number';
} else {
    echo $notnumber . ' is NOT a number';
}

?>

The Code above gives result:

88205052E00 is a number

How can I get the result to be: 88205052E00 is NOT a number?

like image 996
Cyborg Avatar asked Dec 19 '18 18:12

Cyborg


People also ask

How do you check if a string is a number PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

How do you check if a number is exponential in PHP?

The is_numeric() function in the PHP programming language is used to evaluate whether a value is a number or numeric string. Numeric strings contain any number of digits, optional signs such as + or -, an optional decimal, and an optional exponential. Therefore, +234.5e6 is a valid numeric string.

What is a numeric string?

As the name suggests, numeric string is the string of numbers however not limited to string of 0-9. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus "+0123.45e6" is a valid numeric string value.


2 Answers

I will keep the answer incase it helps but as pointed out there are shortcomings with ctype_digit in that it does not like - or ..

More likely then you want to use ctype_digit which checks if all of the characters in the provided string, text, are numerical.

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

<?php

$s = "88205052E00";

if(ctype_digit($s)){
    echo "Yes";
} else {
    echo "No";
}

returns no.

like image 65
nerdlyist Avatar answered Oct 10 '22 23:10

nerdlyist


Just use a regular expression:

<?php
if (preg_match("/^\-?[0-9]*\.?[0-9]+\z/", $notnumber)) {
    echo "$notnumber is numeric\n";
} else {
    echo "$notnumber is not numeric\n";
}

Results:

   1234 is numeric
1234E56 is not numeric
  -1234 is numeric
  .1234 is numeric
 -.1234 is numeric
 -12.34 is numeric
like image 36
miken32 Avatar answered Oct 11 '22 01:10

miken32