0

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.

8
  • 4
    Are you sure you need this? If you only need to access individual characters, you can just use [] on the string itself. E.g. $name[1] will get you o. Commented Jul 26, 2010 at 14:10
  • @Matti Virkkunen, this method is not good for non-english letters (russian, for example). Commented Jul 26, 2010 at 14:11
  • 1
    @Kirzilla: That would've been a good thing to mention in your post, since many of the built-in functions don't support multibyte characters either. The multibyte string extension might help you, but I avoid PHP altogether due to its abysmal string handling. Commented Jul 26, 2010 at 14:13
  • @Kirzilla: I'm curious now, what happens with non-Latin alphabets? Commented Jul 26, 2010 at 14:13
  • 1
    @Matti: this isn't Kirzillas post, we don't know what chad needs... Commented Jul 26, 2010 at 14:15

5 Answers 5

13

There's str_split for that.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 i'd suggested the explode function but of course, that requires a delimeter.
5

You already can access your string using [] operator.

For example :

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

You then just have to use explode.

Comments

3
$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')

Comments

1

$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];

Comments

-1

Chad,

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

jim

4 Comments

Chad - Artefacto's suggestion is the best bet!!
I wouldn't use w3schools, nor I would use explode().
truth, in truth neither would I :). thanks for being courteous enough to leave a reason for the -1. all the best..
I wasn't the one who DV'd you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.