Reputation: 6561
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.
Upvotes: 0
Views: 7328
Reputation: 51817
$str = "John Smith";
$arr = str_split($str);
note: maybe you don't have to do this, you can simply use a string like it's an array to get every character ($str[1]
to get an 'o')
Upvotes: 3
Reputation: 3873
You already can access your string using []
operator.
For example :
$var = "bonjour";
echo $var[0];
> 'b'
You then just have to use explode.
Upvotes: 5
Reputation: 8195
$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];
Upvotes: 1
Reputation: 22485
Chad,
try using the php 'explode' function http://www.w3schools.com/php/func_string_explode.asp
jim
Upvotes: -1