PHP: Convert variable to array
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.
There's str_split
for that.
You already can access your string using []
operator.
For example :
$var = "bonjour";
echo $var[0];
> 'b'
You then just have to use explode.
$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')
$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];
Chad,
try using the php 'explode' function http://www.w3schools.com/php/func_string_explode.asp
jim
精彩评论