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. I'm wondering, would something like this work:
is_numeric($string[0]);
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()
.
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]) ) {
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With