Thursday, November 19, 2015

PHP: Split string into array, like explode with no delimiter

http://stackoverflow.com/questions/2170320/php-split-string-into-array-like-explode-with-no-delimiter

I have a string such as:
"0123456789"
and need to split EACH character into an array.
I for the hell of it tried:
explode('', '123545789');
But it gave me the obvious: Warning: No delimiter defined in explode) ..
How would I come across this? I can't see any method off hand, especially just a function
shareimprove this question

8 Answers

up vote 81 down vote accepted
$array = str_split("0123456789bcdfghjkmnpqrstvwxyz");
str_split also takes a 2nd param, the chunk length, so you can do things like:
$array = str_split("aabbccdd",2);

// $array[0] = aa
// $array[1] = bb
// $array[2] = cc  etc ...
You can also get at parts of your string by treating it as an array:
$string = "hello";
echo $string[1];

// outputs "e"