Reputation: 506
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
Upvotes: 2
Views: 3686
Reputation: 781235
$str[$i]
doesn't treat it as an array. This is just a shorthand notation for substr($str, $i, 1)
.
You can use str_split()
to get an array of characters from a string:
foreach (str_split($str) as $letter)
From the documentation:
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in
$str[42]
.
Upvotes: 6