floatleft
floatleft

Reputation: 6561

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.

Upvotes: 0

Views: 7328

Answers (5)

oezi
oezi

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

Guillaume Lebourgeois
Guillaume Lebourgeois

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

Rob
Rob

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

jim tollan
jim tollan

Reputation: 22485

Chad,

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

jim

Upvotes: -1

Artefacto
Artefacto

Reputation: 97845

There's str_split for that.

Upvotes: 13

Related Questions