Code

PHP Explode Each Character Function

This function is like PHP's explode() funtion, but instead of having a delimiter, it separates each character into it's own array piece.

For example, explodeEachChar('cat') would return array(0 => 'c', 1 => 'a', 2 => 't').

<?php

function explodeEachChar($x) {
    $c = array();
    while (strlen($x) > 0) {
        $c[] = substr($x,0,1);
        $x = substr($x,1);
    }
    return $c;
}

?>

Note: Of course, if you're on PHP 5 or greater, this can be done more simply using PHP's built-in str_split() function.


2 Comments

Lyndon
May 19, 2011, 7:06 am
Thanks for the code. Just for future reference to anyone else using this:

Replace: while (strlen($x > 0))
With: while (strlen($x) > 0)

Otherwise it misses out the last character of the string.
Robert James Reese
May 19, 2011, 11:02 am
Thanks Lyndon. You're right, I had a typo. I fixed it in the code up above too.

Leave a Comment

Name
Email
Website
Comment
Name and email are required. Your email will not be published.

This post was published on Sunday, November 8th, 2009 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our Terms & Conditions.

Copyright © 2012, Ink Plant. All rights reserved.