0 0 Votes

PHP: Read out first Character from String

Question by Guest | 26/06/2015 at 23:14

How is it possible to specify 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?


Stefan Trost

Show Profile | Message
0Best Answer
0 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

First of all, it is possible to access individual characters of a string by 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 I am showing in the example, is using the PHP function substr() for the same purpose. As starting position (second parameter) of our substring we are passing the beginning of the 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.
28/06/2015 at 23:48

ReplyPositive Negative

Related Topics

Save Binary Data as String
Question | 1 Answer

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.


Ask your own question or write your own articles on askingbox.com. How to do.