Home
PHP
Loop Over String Chars
Updated Nov 28, 2023
Dot Net Perls
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.
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.
$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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 28, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen