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+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov