11 Vote

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?

ReplyPositiveNegativeDateVotes
3Best Answer3 Votes

Here are two examples showing two possibilities to extract the first character from a string:

$s = "abc";

echo $s[0];             // a
// or
echo substr($s, 0, 1);  // a

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

ReplyPositive Negative
-11 Vote

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:

echo $s{0}; // a

Greetings, Zen
2019-02-14 at 20:55

ReplyPositive Negative
11 Vote

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

Positive Negative
Reply
Reply

Related Topics

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.