str_split()


today i learned some neat little trick in php.

lets say i have string called $string and the value is wallpaperama. if you use the str_split() you can split the $string into each letter, for example, i have this code:


<?
$string = 'wallpaperama';
$string = str_split($string);
echo '<pre>';
print_r($string);
echo '<pre>';
?>


the oupout will look like this:
Array
(
[0] => w
[1] => a
[2] => l
[3] => l
[4] => p
[5] => a
[6] => p
[7] => e
[8] => r
[9] => a
[10] => m
[11] => a
)


ok, how about if you want to limit the number of elements in the array. lets say i only want only wallpaper instead of wallpaperama?

well, since wallpaperama has 12 letters, and if i remove the last three, then im only left with wallpaper, so this is how i would do it

well, in that case when you run the output, just make sure when you do it with your loop, you can specify the number of steps is the limit.

another trick you can use this function is by splitting the word but instead of making it into a single element, how about if you split it of two, three or four.. or whatever you want. for example, my $string is wallpaperama, so i have 12 characters, lets say i want to divide that into 4 separate elements, all i would have to do is add the number in the function. i will show you the sample code:


<?
$string = 'wallpaperama';
$string = str_split($string,3);
echo '<pre>';
print_r($string);
echo '<pre>';
?>


this is is the output:
Array
(
[0] => wal
[1] => lpa
[2] => per
[3] => ama
)


are you familiar with the explode() function in php? if not, take a look at it, you can split an string with a common denominator also.
for example i have this:

$foo = '1|2|3|';
$foo = explode('|',$foo);
print_r($foo);

this is how the output will look like:
[0] => 1
[1] => 2
[2] => 3
[3] =>


hope this helps