Suppose we have a string
with some characters in it. In PHP programs, it is often necessary to loop over and test these characters in some way.
With for and foreach
, we can access the characters in a string
. But we need to access the string
's length, and possibly split the string
first.
To begin we introduce a 5-byte string
containing the word "bird" and a period. This is the data we run our loops on. We loop over the string
in 2 different ways.
for
-loop. We must access the length of the string
with strlen()
first.foreach
-loop over the string
. We convert the string
into an array with str_split
, and then foreach
will work.string
with strlen
and the indexing operation. For multi-byte characters, we need a different function.$value = "bird."; // Version 1: get string length, then loop over string. $len = strlen($value); echo "Strlen = {$len}\n"; // Loop over the string indexes and access each char. for ($i = 0; $i < $len; $i++) { $c = $value[$i]; echo "Char = " . $c . "\n"; } // Version 2: separate the string into letters, and loop over each letter. $chars = str_split($value); foreach ($chars as $c) { echo "Foreach char = {$c}\n"; }Strlen = 5 Char = b Char = i Char = r Char = d Char = . Foreach char = b Foreach char = i Foreach char = r Foreach char = d Foreach char = .
Looping over, and testing, individual bytes (or chars) from a string
is often required. In ASCII strings, bytes are the same thing as chars.
Often when we need to access the individual bytes from a string
, it is useful to simply convert the string
to an array. This can be done with str_split()
.