Categories
PHP Tips & Tutorials

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.

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.

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

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

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.

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.