Benjamin W
Benjamin W

Reputation: 2848

Validate positive integers only

Problem

I need to validate some input. It should accept positive integers only. So far, my code is not working properly.

My code

if ( !is_numeric($data['dollar']) {
  return FALSE; 
}

Examples

0 // TRUE
1 // TRUE
-1 // FALSE
0.9 // FALSE

Upvotes: 2

Views: 775

Answers (4)

Sam Battat
Sam Battat

Reputation: 5745

if ( !ctype_digit($data['dollar']) ) { return FALSE; }

http://php.net/ctype_digit

Upvotes: 4

bishop
bishop

Reputation: 39414

You can use the validation functions:

$type    = FILTER_VALIDATE_INT;
$options = [ 'min_range' => 1, 'max_range' => PHP_INT_MAX ];
if (false === filter_var($data['dollar'], $type, [ 'options' => $options ])) {
    return FALSE;
}

See it online at 3v4l.org.

Upvotes: 0

Arzoo
Arzoo

Reputation: 106

You can use is_int() instead of is_numeric()

Upvotes: -1

d3no
d3no

Reputation: 121

You can use regex below to solve your problem

return preg_match("/^[0-9]*$/",$data['dollar']);

Upvotes: -1

Related Questions