tags:

views:

77

answers:

5

I'm trying to convert a variable to an array and split each character using PHP.

So say I have a variable $name = 'John Smith'; How do I convert it to:

array('J','o','h','n',' ','S','m','i','t','h');

Notice the space between John and Smith as well.

Thank you.

+11  A: 

There's str_split for that.

Artefacto
+1 i'd suggested the explode function but of course, that requires a delimeter.
jim
A: 

Chad,

try using the php 'explode' function http://www.w3schools.com/php/func_string_explode.asp

jim

jim
Chad - Artefacto's suggestion is the best bet!!
jim
+1  A: 

$array = preg_split('//', $string);

However, you can treat strings as character arrays in php.

$string = 'foobar';
for($i=0; $i<strlen($string); ++$i) echo $string[$i];
Rob
+4  A: 

You already can access your string using [] operator.

For example :

$var = "bonjour";
echo $var[0];
> 'b'

You then just have to use explode.

Guillaume Lebourgeois
A: 
$str = "John Smith";

$arr = str_split($str);

note: maybe you don't have to do this, a character of a string like it's an array ($str[1] to get an 'o')

oezi
what the heck? why do i get a downvote for this?
oezi