Loop Through Letters in a String with PHP

September 23rd, 2011 - Posted by Steve Marks to PHP, Web Development.

Iterating through a string to get each letter can be easily achieved with PHP. The example below shows how this can be done with a for loop:

$string = "HelloWorld";

for ($i=0; $i<strlen($string); $i++) {
    echo $string[$i].".";
}

// Outputs: H.e.l.l.o.W.o.r.l.d.

Notice how we reference the individual letters like we would an array element. This also means we can get the letter at a certain point by referencing the letters index like so:

$string = "HelloWorld";

echo $string[4];

// Outputs: o
Tags:
This entry was posted on Friday, September 23rd, 2011 at 9:37 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first