Recently, I came across the need of going through a string
to act on his letter
As far as I know, a string
in PHP is represented as an array
of bytes as stated in the doc.
Then I naturally wrote :
$str = 'Hello';
foreach ($str as $letter) {
doMyThingsOnLetter($letter);
}
Sadly, I got an error saying me that I have provided foreach an invalid argument
I know that this work :
$str = 'Hello';
for($i = 0; $i < strlen($str); $i++) {
doMyThingsOnLetter($str[$i]);
}
So here, $str
is considered as an array but by a foreach
we got an error for invalid argument (while it states in the doc it allows arrays)
So I wonder if there is some sort of different type of array for the representation of the string itself in PHP or is it only the way foreach handle array differently ?
PS: I know str_split()
exist for this purpose but that's not my concern here