I was trying to find a quick and easy method to check if the first letter in a string is a number. A lot of the functions and methods I\'ve seen on S.O seem over complicated
An easier way might be:
is_numeric(substr($string, 0, 1))
It tackles the problem of a possible empty string (that has no first character) by using substr()
. substr()
returns false
in the case of an empty string, and false
is not recognized as a number by is_numeric()
.
Yes, it's a clean way of doing it, but use ctype_digit instead since it only allows the numbers 0 to 9 and nothing else.
I don't know why that answer is deleted, but the correct answer is
preg_match('/^\d/', $string);
Why? Because it provides a standard way to query strings. Normally, you have to answer many similar questions in your application:
etc, etc. Without regular expressions you'd have to invent a different combination of string functions for each case, while REs provide the uniform and standard interface, which you simply reuse over and over again. This is like algebra compared to arithmetic.
It won't work on empty strings, so you should check the offset prior accessing it:
$result = isset($string[0]) ? is_numeric($string[0]) : false;
No, that would not work. You might get "Notice: Uninitialized string offset: 0" notice. To make it work, add strlen():
if ( strlen($string) > 0 && is_numeric($string[0]) ) {
}