Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I convert a string to an array? For instance, I have this string:

$str = 'abcdef';

And I want o get:

array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
}
share|improve this question
5  
In case you need to access a specific offset in the string, you can do so without splitting the string. Strings can be used with Array Access notation. $str[0] would return 'a'. You cannot use foreach or any of the array functions on it though then. – Gordon Jul 19 '10 at 7:55

3 Answers

Every String is an Array in PHP

So simply do

$str = 'abcdef';
echo $str[0].$str[1].$str[2]; // -> abc
share|improve this answer

You can loop through your string and return each character or a set of characters using substr in php. Below is a simple loop.

$str = 'abcdef';
$arr = Array();

for($i=0;$i<strlen($str);$i++){
    $arr[$i] = substr($str,$i,1);
}

/*
OUTPUT:
$arr[0] = 'a';
$arr[1] = 'b';
$arr[2] = 'c';
$arr[3] = 'd';
$arr[4] = 'e';
$arr[5] = 'f';
*/
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.