Loop Through Letters in a String with PHP

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

Share

Related Posts

- Converting a PHP Array to a Query String… And Back Again
- Using PHP to Capitalize a Word or Sentence
- Generating a Unique ID Using PHP and MySQL
- Getting the First Word of a String with MySQL
- Removing All Spaces From a String Using Javascript

Leave a Reply

Spam protection by WP Captcha-Free