Split a word letter by letter
Submitted by Pujan on Mon, 10/13/2008 - 17:00
Tagged:
We have often used the function explode() to split a string by a certain string delimeter(eg: ":","~","-","," e.t.c). However,you may seldom come across a situation where you need to split a word letter by letter without any delimeter separating it. There's a simple function "str_split" for this purpose. This function splits a string to an array.
It's usage is given below:
$str = "abcdefgh"; // store value in a variable
$arr1 = str_split($str); //split the string and store its value in an array
echo "
"; print_r($arr1); // print the array foreach($arr1 as $key=>$val){ //applying style to individual letters in an array echo "$val"; } echo ""; Alternative Method Usage:$str = "abcdefgh"; // store value in a variable $strlength=strlen($str); // retrieving the length of the string for($x=0;$x<$strlength;$x++) { // run a loop for the length of the string // print each letter using the substring function and print a string of length 1 echo "".substr($str,$x,1).""; }