Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to test if a variable is a number in PHP?

Tags:

php

integer

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.

like image 770
Leo Jiang Avatar asked Feb 22 '23 04:02

Leo Jiang


2 Answers

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

like image 177
Tim Cooper Avatar answered Apr 26 '23 16:04

Tim Cooper


You're looking for is_numeric().

http://php.net/is_numeric

like image 25
Xavura Avatar answered Apr 26 '23 18:04

Xavura