qinHaiXiang
qinHaiXiang

Reputation: 6419

Split a string into an array of characters

How can I split a string like:

DEFGHIJKLMN

into an array of characters like:

$diskVolume = array('D','E','F','G','H','I','J','K','L','M','N');

explode() doesn't work for this kind of string because there are no delimiters on which to split the string.

Upvotes: 0

Views: 488

Answers (3)

Truongnq
Truongnq

Reputation: 367

Should use str_split or

for($i=0;$i<strlen($diskVolume);$i++){
echo $diskVolume[$i];
}

Upvotes: 0

Mchl
Mchl

Reputation: 62359

You can actually use array access to read from strings:

>> $a = 'CDEFGHIJKLMO';
'CDEFGHIJKLMO'
>> echo $a[2];
E

However you can't use it as an argument for foreach() and similar constructs/functions

Upvotes: 1

BoltClock
BoltClock

Reputation: 723428

Use str_split() to split a string into its individual characters:

$diskVolume = str_split($string);

Upvotes: 7

Related Questions