In this quick post, I will tell you how to return the first character of a string in PHP.
I work with string manipulation in PHP quite a bit and remembering the little nuances can be a challenge. And, often the returned searches in Google are absolutely incorrect or outdated. For example, I just Googled “PHP return first character of string” and received non-answers and, even worse, extremely long pontifications from people at stackoverflow.com that were patently wrong or way too complex than needed to be.
So, I write these quick little posts for both of us so that we can quickly remember. Here is how to quick truncate a PHP string to the first character.
Return First Character of a String in PHP
The PHP code to return the first character uses the PHP substr syntax. The syntax is explained in the sample below:
<? // this file shows how to remove the first character of a string // you can upload it to your server to see exactly how it works $fname = "Richard"; $fname1=substr($fname,0,1); // return the first character (0) of the string and only return 1 character echo "The first character of the string is <b>$fname1</b>." ?>
I hope this helps someone out there trying to achieve the same. Want another little tidbit of wisdom on the first character of a string? Check out this post entitled PHP Delete First Character In String where I also offer some string challenges 🙂