Loop over each character in a string

Loop over each character in a string

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Loop over each character in a string

When you need to treat a string as an array of characters, the immediate instinct is often to reach for array_map, array_filter, or a standard foreach loop. While these tools are powerful, they operate on arrays, not strings directly. The core challenge lies in bridging that gap: converting a string into an iterable collection without sacrificing performance or readability.

The solution you found, which manually constructs an array using a for loop and strlen, is functionally correct but feels clunky because it requires explicit memory management and index handling. In modern PHP, there is indeed a cleaner approach that leverages built-in language features to make strings iterable directly, eliminating the need for manual array construction entirely.

The Iterator Approach

The most direct answer to "Is there a way to make the string iterable?" lies in using StringIterator. This class implements the Iterator interface specifically designed to traverse strings character by character. By wrapping your string in this iterator, you can immediately drop into a foreach loop without ever creating an intermediate array in memory.

Here is how you can refactor the manual loop logic:

$s1 = "textasstringwoohoo";

// Iterate directly over characters using StringIterator
$iterator = new \StringIterator($s1);

foreach ($iterator as $curChar) {
    // $curChar is a single character string (e.g., 't')
    echo $curChar . "\n";
}

This approach addresses the "iterable" requirement elegantly. It allows you to use foreach natively while keeping memory usage low, as PHP handles the iterator internally rather than allocating an array of every character upfront. If you need to apply functions like array_map or array_filter, this direct iteration isn't strictly possible because those functions expect arrays. However, you can achieve the same result by chaining higher-order functions with a helper that converts the iterator back to an array if necessary, though usually, direct iteration is preferred for readability.

Converting Between Strings and Arrays

Regarding your second question about a better way to build the character array from a string: yes, there is a more concise method than writing a custom for loop. While PHP does not have a built-in str_split() function that returns an associative array by default in all versions, the standard str_split() function has been available since PHP 4.

The manual loop you wrote essentially replicates what str_split does under the hood but with more verbose syntax. Here is the concise alternative:

$s1 = "textasstringwoohoo";
$arr = str_split($s1); // Returns a numerically indexed array of characters

// Now you can seamlessly use array_map, array_filter, etc.
$ascval = array_map('ord', $arr);

$evenAsciiOnly = array_filter(
    $arr, 
    fn($char) => ord($char) % 2 === 0
);

This str_split function is the industry standard for converting a string into an iterable character array. It returns a numerically indexed array where each element is a one-character string. This makes your existing logic for mapping ASCII values or filtering characters drop-in compatible without any changes to your function definitions.

The Reverse Operation

You also asked about the other direction: turning that character array back into a string. PHP provides implode() for this exact purpose. It takes a separator (usually an empty string) and an array, joining the elements into a single string.

$backToString = implode('', $arr); // Joins characters back into "textasstringwoohoo"

Performance Considerations and Trade-offs

When deciding between StringIterator and str_split, the choice often comes down to memory constraints versus functional programming needs. If you are processing a massive text file line-by-line or stream processing large datasets, using StringIterator is superior because it avoids allocating an entire array in RAM for every character. It processes the data lazily.

Conversely, if you need to perform vectorized operations like array_map or complex filtering logic that requires random access to elements, converting to an array via str_split is necessary. The overhead of creating the array is negligible for typical string lengths (up to several megabytes), but it becomes a factor in high-throughput scenarios where memory allocation is the bottleneck.

The manual loop solution you originally drafted works perfectly fine and offers maximum control over index handling, but unless you have a specific reason to manage indices manually, leveraging str_split or StringIterator adheres to the principle of using built-in abstractions provided by the language. These tools abstract away the pointer arithmetic and length checking, reducing the chance of off-by-one errors and making the intent of your code immediately obvious to other developers.

Our network