Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to Integer and test it?

I've a problem. I'm scrapping a txt file and extracting an ID. The problem is that the data is not consistent and I have to evaluate the data.

Here is some code:

$a = "34";
$b = " 45";
$c = "ddd556z";


if (  ) {

    echo "INTEGER";
} else{ 

    echo "STRING";
}

I need test if the values $a, $b or $c are Integers. What is the best way of doing this? I have tested to "trim" and the use "is_int" but is not working as expected.

Can someone give me some clues?

like image 260
André Avatar asked Dec 22 '22 12:12

André


1 Answers

The example below will work even if your "int" is a string $a = "number";

is_numeric()

or

preg_match( '/^-?[0-9]+$/' , $var )  // negative number © Piskvor

or

intval($var) == $var

or (same as last)

(int) $var == $var
like image 198
dynamic Avatar answered Dec 24 '22 01:12

dynamic