Practical Web Programming

Monday, January 26, 2009

PHP: How to Print Each Character in a String

With PHP's growing string functions, you will be able to find one that will suit your need. For instance the substr, this function will return the portion of string specified by the start and length parameters. You can you use it to print each character in a string.

Here's an example.

    
$string = "Joel P. Badinas";

for ($i = 0; $i < strlen($string); $i++)
{
print "[" . $i . "] " . substr($string, $i, 1) ."<br/>";
}

?>


The output will be like this.

  [0]  J
[1] o
[2] e
[3] l
[4]
[5] P
[6] .
[7]
[8] B
[9] a
[10] d
[11] i
[12] n
[13] a
[14] s

2 comments:

Anonymous said...

your example is slow.

$string = "Joel P. Badinas";
$string_len = strlen($string);

for ($i = 0; $i < $string_len); $i++)
{
print "[" . $i . "] " . $string[$i] ."
";
}

?>

Joel Badinas said...

@Anonymous,

How slow? If it takes several seconds for the output to display then there must be something wrong with your PHP server.

The for loop iterates only for 15 times so it will not take PHP 1 second to load it.

Recent Post