Aswin Lutchanah

Hybrid Social Media Manager

Php function – check if characters in a string are numerical

I was looking for a way to check if a string contained only numerical values.  I thought that the php function is_numeric() would do the job. I was wrong.

echo is_numeric(555); // 1
echo is_numeric(55.55); // 1
echo is_numeric(+55.55); // 1
echo is_numeric(-55.55); // 1
echo is_numeric(-+55.55); // 1

Facebook ids (for developers)

Php has a function (ctype_digit()) that suits my needs concerning this matter. In fact, I was looking for a way to check the different ids provided by Facebook and that transited through my Facebook Apps. I needed a server side verification for those ids. As you might already know, Facebook ids tend to be very long and considering them as integers could end up being very tricky. So, php functions like is_int() or intval() are useless in this case because they are system dependent (32 bits, 64 bits, etc..).

Php function ctype_digit()

ctype_digit() checks whether the whole string contains only digits ! Therefore, you don’t bother about the length of the string (Facebook id or any other id). With this php function, you will know if it contains only digits without any signs such as “+,-,.,etc…”.

echo ctype_digit('555'); // 1
echo ctype_digit('55.55'); //
echo ctype_digit('+55.55'); //
echo is_numeric('-55.55'); //
echo ctype_digit('-+55.55'); //

Alternative with a regular expression

This was my initial solution to the problem.

function isValidBigInteger($sString) {
        return preg_match('/^[0-9]+$/', $sString);
echo isValidBigInteger('555');//1
echo isValidBigInteger('55b');//0

Posted In: PHP, SMO, Web Development

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.