PHP: Looping through the characters of a string.

This is a simple guide on how to loop through the characters of a string in PHP.

First of all, you need to know about the function str_split.

Basically, this function converts a given string into an array. In other words, the string is “split up” and each character is then added as an element to an array.

Note that this will also include special characters and whitespaces.

A short example.

<?php
$myString = "abc123 90!p";
$myArray = str_split($myString);

var_dump($myArray);

If you run the code above, you’ll see that the $myArray variable is an array that contains each character from our string.

Then, you just loop through it like so.

<?php

$myString = "abc123 90!p";
$myArray = str_split($myString);

foreach($myArray as $character){
    echo $character . "<br>";
}

The code above will loop through the characters and print them out on separate lines.

As I said, it’s actually pretty simple!