PHP: How to process a string one byte (character) at a time

If you want to loop through a literal string in PHP and have the opportunity to look and process each of the characters one character at a time, use the following snippet:

$string = "Hooray";
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    echo $string[$i].', ';
}

There you go, just use $string_variable[$char_index] to access each of the characters in a string. With non-multi-byte encoding, a byte is a character.

strlen() function returns the length of a string.

5 thoughts on “PHP: How to process a string one byte (character) at a time”

  1. Hey,

    Thanks for the tip – I always forget this. Just as a quick heads up though – It is much more efficient to put the call to strlen outside of the for loop. That way it only needs to be evaluated once, rather than for each iteration of the loop.

    e.g.

    $string = “Hooray”;
    $j = strlen($string);
    for ($i = 0, $i < $j; $i++) {
    echo $string[$i].', ';
    }

    1. Read the post before answering anything.

      Look precisely at the commas and semicolons positions in the original for() instruction, and you will notice that the strlen() call is made only ONCE.

  2. how to process(read) each word in a sentence and then through the sentence that we type in, it will display articles that related..
    just like Google
    please help…TQ

Comments are closed.

Scroll to Top