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.
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