A character from a string

March 29th, 2005. Tagged: PHP certification

You can get a specific character from a string as if the string was an array.
< ?php
$s = 'PHP';
echo $s[0]; // will print "P"
?>
This syntax may be confusing, because someone looking at the code might expect that $s is an array. Well it is an array, an array of characters, but that's not the point. The point is that if might be confusing.

The same result may be achieved with curly braces.
< ?php
$s = 'PHP';
echo $s{1}; // will print "H"
?>
The numbering is zero-based, the first character in the string has offset 0.

Tell your friends about this post: Facebook, Twitter, Google+

One Response

  1. Hello there, I discovered your website by the use of Google whilst searching for a similar subject, your web site came up, it looks great. I’ve added to my favourites|added to my bookmarks.

Leave a Reply