Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check that a string holds a number

Short answer

is_numeric() returns true for integers and floats in a string:

<?php
 
var_dump(is_numeric('42'), is_numeric('3.14'), is_numeric('12abc'));

Output:

bool(true)
bool(true)
bool(false)

Digits only

is_numeric() also accepts '1e5', '-7' and ' 5'. If only digits are wanted, use ctype_digit():

<?php
 
var_dump(is_numeric('1e5'), ctype_digit('1e5'));
var_dump(ctype_digit('2026'), ctype_digit(''));

Output:

bool(true)
bool(false)
bool(true)
bool(false)

An integer within bounds

filter_var() validates and returns the number at once:

<?php
 
var_dump(filter_var('25', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]));
var_dump(filter_var('250', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]));

Output:

int(25)
bool(false)

Functions used in this recipe

  • is_numeric — Checks whether a value is a number or a numeric string.
  • filter_var — Validates or sanitises a value by a given rule.
  • preg_match — Tests a string against a regular expression.

Thanks for reading!

Donate to the site — we work hard for you.