PHP: Read out first Character from String
Question by Guest | Last update on 2024-01-16 | Created on 2015-06-26
How is it possible to determine the first character from an arbitrary string in PHP?
For example, given the string "abc", I would like to get the letter "a" as a result.
Is there any function for that in PHP?
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
PHP: Get first Digit of Number or String
Tutorial | 0 Comments
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
HTACCESS: Simplify URL
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.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Here are two examples showing two possibilities to extract the first character from a string:
The first example shows how to access individual characters of a string using square brackets. The first character of a string has the position 0, so we can read out this character via $s[0].
The second possibility shown in the example, utilizes the PHP function substr() for the same purpose. As starting position (second parameter) of our desired substring we are passing the beginning of the input string (that is 0) and as number of characters to be extracted (third parameter) we are specifying 1 to get exactly the first character from the string.
Last update on 2024-01-16 | Created on 2015-06-28
Well, querying an offset in square brackets is no longer permitted since PHP 7 at the latest and substr is of course quite expensive in terms of performance.
I recommend querying the offset in curly brackets, so:
Greetings, Zen
2019-02-14 at 20:55
The opposite is the case. While previously both were possible (square brackets and curly brackets produced the same result and could be used interchangeably), as of PHP 8.0.0 only the square bracket syntax is supported anymore. The same applies, for example, also to arrays.
2019-02-16 at 23:58