11 Vote

PHP: Negative Numbers and ctype_digit

Question by Compi | 2016-06-07 at 21:09

In one of my PHP scripts, I get some data from an HTML form and before processing the input, I would like to check whether there is really an integer number submitted.

Up to now, I have used the PHP function ctype_digit() for that. This is working quite well as long as the number or digit is positive. However, now I would also like to allow negative numbers and ctype_digit() always returns false for them.

What can I do to validate both, positive and negative numbers?

-2Best Answer2 Votes

Using ctype_digit(), you can only test whether the passed string is consisting of digits (0-9). The function does not check whether the string is holding a valid integer number that can possibly be negative.

However, you can use this regular expression and preg_match() for your purpose:

$teststr = "-1";

if (preg_match("/^-?[1-9][0-9]*$/", $teststr)) {
  echo 'String is a positive or negative number.';

This if statement with this regular expression ensures:

  • that there can be a minus sign at the beginning of the string, but that must not be one
  • that the number must start with a digit from 1 to 9, a 0 at the beginning is not allowed
  • that this starting number can be followed by an arbitrary number of other digits from 0 to 9, but must not

So, with this code, you can identify negative as well as positive numbers of an arbitrary length.
2016-06-08 at 20:12

ReplyPositive Negative

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.