php explode all characters [duplicate]
Asked Answered
D

4

55

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?

Demonstrative answered 21/3, 2012 at 23:32 Comment(0)
L
121

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
)
Lachrymatory answered 21/3, 2012 at 23:34 Comment(1)
what about accents?Corridor
S
8

Use the str_split function.

$array = str_split( 'testing');
Subbase answered 21/3, 2012 at 23:33 Comment(0)
F
6
$string = "TEST";

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

There is no need to explode it

Fatuitous answered 21/3, 2012 at 23:34 Comment(4)
How would you create array from the string, each character as a separate element in the array?Eadith
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.Fatuitous
Oh, really? See this: codepad.org/SRsULXQE ("Warning: array_map(): Argument #2 should be an array"). -1Eadith
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.Subbase
I
0

TO SPLIT string into ARRAY its best to use

$arr= str_split($string);
Ivanivana answered 21/2, 2015 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.