Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert string to array

Tags:

arrays

php

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"
}
like image 501
Richard Knop Avatar asked Jul 19 '10 07:07

Richard Knop


People also ask

Which function in PHP allow you to convert a string to an array?

PHP | str_split() Function The str_split() is an inbuilt function in PHP and is used to convert the given string into an array.

What is implode PHP?

Definition and Usage The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.

What is explode in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string.


2 Answers

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

like image 188
robertbasic Avatar answered Sep 17 '22 17:09

robertbasic


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';
*/
like image 23
svarlitskiy Avatar answered Sep 19 '22 17:09

svarlitskiy