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.
You should also read:
- PHP String Length function to Get Length of Strings in PHP
- PHP: Return and Get the Last Letter / Character of a String
- PHP: Sort and Order Array Items / Elements / Numbers Naturally so 2 Comes before 10
- PHP: True empty() function to check if a string is empty or zero in length
- PHP: Check if A String Contain Only Uppercase / Capital Letters


Facebook
Twitter
Google Plus
{ 5 comments… read them below or add one }
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].', ';
}
This code more faster when execute bcause only run strlen once at time :)
regards
hahaha~ i still remember the Big-O mentioned by my lect. lol~! nyway, thanks a lot Yang~! =]
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