Is there a nice way to iterate on the characters of a string? I\'d like to be able to do foreach
, array_map
, array_walk
, array_
Iterate string:
for ($i = 0; $i < strlen($str); $i++){
echo $str[$i];
}
If your strings are in Unicode you should use preg_split
with /u
modifier
From comments in php documentation:
function mb_str_split( $string ) {
# Split at all position not after the start: ^
# and not before the end: $
return preg_split('/(?<!^)(?!$)/u', $string );
}
Step 1: convert the string to an array using the str_split
function
$array = str_split($your_string);
Step 2: loop through the newly created array
foreach ($array as $char) {
echo $char;
}
You can check the PHP docs for more information: str_split