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

by Yang Yang on April 23, 2009

Share This Article:
Subscribe to Kavoir: blog feed

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.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 5 comments… read them below or add one }

Dave November 10, 2010 at 6:26 am

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].', ';
}

Reply

Buzzknow November 14, 2010 at 9:54 pm

This code more faster when execute bcause only run strlen once at time :)

regards

Reply

Fikri November 22, 2010 at 9:08 pm

hahaha~ i still remember the Big-O mentioned by my lect. lol~! nyway, thanks a lot Yang~! =]

Reply

Frosty December 9, 2011 at 6:23 pm

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.

Reply

apocalypse November 19, 2011 at 12:57 pm

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

Reply

Leave a Comment

Previous post:

Next post: