53

I'm looking for the equivalent of what in js would be 'this is a string'.split('') for PHP.

If I try $array = explode('', 'testing'); I get an error Warning: explode() [function.explode]: Empty delimiter in

Is there another way to do this?

qwertymk
  • 34,200
  • 28
  • 121
  • 184

4 Answers4

120

As indicated by your error, explode requires a delimiter to split the string. Use str_split instead:

$arr = str_split('testing');

Output

Array
(
    [0] => t
    [1] => e
    [2] => s
    [3] => t
    [4] => i
    [5] => n
    [6] => g
)
Josh
  • 8,082
  • 5
  • 43
  • 41
8

Use the str_split function.

$array = str_split( 'testing');
nickb
  • 59,313
  • 13
  • 108
  • 143
6
$string = "TEST";

echo $string[0];  // This will display T

There is no need to explode it

Josh
  • 8,082
  • 5
  • 43
  • 41
Mark Roach
  • 1,039
  • 9
  • 20
  • How would you create array from the string, each character as a separate element in the array? – Tadeck Mar 21 '12 at 23:37
  • 1
    PHP looks at it as an array automatically if you treat it as one, and gives each character a key based on it's position. – Mark Roach Mar 21 '12 at 23:41
  • Oh, really? See this: http://codepad.org/SRsULXQE ("_Warning: array_map(): Argument #2 should be an array_"). -1 – Tadeck Mar 21 '12 at 23:44
  • 2
    He meant to say: "PHP will index a string like an array". But it is not an array and cannot be used on functions that require array inputs. However, you can loop over a string and extract an individual character with the same notation as an array with a `for` loop over the `strlen` of the string. – nickb Mar 21 '12 at 23:48
0

TO SPLIT string into ARRAY its best to use

$arr= str_split($string);
Manoj Rammoorthy
  • 1,384
  • 16
  • 16