PHP - iterate on string characters
Use str_split to iterate ASCII strings (since PHP 5.0)
If your string contains only ASCII (i.e. "English") characters, then use str_split.
$str = 'some text';
foreach (str_split($str) as $char) {
var_dump($char);
}
Use mb_str_split to iterate Unicode strings (since PHP 7.4)
If your string might contain Unicode (i.e. "non-English") characters, then you must use mb_str_split.
$str = 'μυρτιὲς δὲν θὰ βρῶ';
foreach (mb_str_split($str) as $char) {
var_dump($char);
}
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 );
}