Home
Map
Loop Over String CharsIterate over the bytes or chars in a string using strlen() and the for loop. Consider using a foreach loop.
PHP
This page was last reviewed on Nov 28, 2023.
Loop chars. 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.
Shows a loop
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.
Example. 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.
Version 1 For the first version, we use a for-loop. We must access the length of the string with strlen() first.
Version 2 Here we use a foreach-loop over the string. We convert the string into an array with str_split, and then foreach will work.
foreach
String Split
Important We access the bytes from the string with strlen and the indexing operation. For multi-byte characters, we need a different function.
Shows a loop
$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().
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 28, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.