13

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

$str = 'abcdef';

And I want to 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"
}
1
  • 6
    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. Commented Jul 19, 2010 at 7:55

6 Answers 6

35

Use str_split http://www.php.net/manual/en/function.str-split.php

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

2 Comments

What happens if we instead simply cast it into an array?
Have you tried? It creates something like array([0] => 'string')
6

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';
*/

Comments

5

Every String is an Array in PHP

So simply do

$str = 'abcdef';
echo $str[0].$str[1].$str[2]; // -> abc

3 Comments

The wording of this answer is misleading
This is not true. The fact that you can use [] with a string doesn't make it an array. Try var_dump(is_array("a string")); and you will see it is NOT an array.
Using [] on a string in fact just gives you access to the characters at those positions, the variable type remains as is and is not converted to or from an array if it wasn't already. It's like how "their" and "there" sound the same in English but have different meanings...
2

Note that starting with php 5.5 you can refer to string characters by array indices, which in most cases prevents need for the solution(s) above.

$str = 'abdefg';
echo $str[4]; // output: f

2 Comments

output "f" because counter starts from 0
@Cypherjac - Thanks. Good catch. I've updated the answer.
0

Other solution:

$string = 'abcdef';

$arr = [];

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

Comments

0
<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
echo "<br/>";
print_r($arr2);

?>

more info !!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.