/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] PHP to split a string to every character

Is there a function to split a string to an array with every character?

[FONT=Courier New]myString.split(“”)[/FONT]

This is the javascript function that I want to “simulate”.

Example:

[code=php]$mystring = “foobar”;
$myarray = //something
var_dump($myarray);

/*
and I want it to output something like:

Array(6){ [0]=>”f” [1]=>”o” [2]=>”o” [3]=>”b” [4]=>”a” [5]=>”r” }
*/[/code]

Any ideas? I can’t seem to find it online.

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJul 06.2006 — str_split() can do this, but it's only available in PHP5.

Note however that strings are by default already sort of like pseudo-arrays, in that you can reference any individual character within the string by it's zero-based position:
[code=php]
$string = "abcedfghijk";
echo "The 5th character of the string is: " . $string[4];
[/code]
Copy linkTweet thisAlerts:
@shane_carrauthorJul 06.2006 — Thanks! I didn't know that strings acted like arrays in that way! Thanks! [URL=http://www.webdeveloper.com/forum/showthread.php?t=110174] :rolleyes: [/URL] I like it! Thanks!
Copy linkTweet thisAlerts:
@NogDogJul 06.2006 — Note: I fixed a typo in my example code, above. (I had typed [b]$string[0][/b] when what I meant was [b]$string[4][/b].)
Copy linkTweet thisAlerts:
@dc2000Jul 06.2006 — I'd rather use Regular Expressions for that:[code=php]$str = "abcdefghi jklm";
$a = preg_split("//", $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($a);
[/code]
It's much faster and is more flexible. This sample above will break the string into array, with each element containing a char, i.e.$a[0] == 'a';
$a[1] == 'b';
$a[2] == 'c';
//etc.
Cheers
×

Success!

Help @shane_carr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...