Convert a string to an array using str_split PHP function.

By | March 12, 2013

Hey Folks,

In PHP, You can convert a string to an array using str_split function.

Syntax:

array str_split ( string $string [, int $split_length = 1 ] )

/* $string=The input string.
$split_length=Maximum length of the pieces. */

Example:

<?php

$str = "Awesome World";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

echo "<pre>";
print_r($arr1); 
print_r($arr2);
echo "</pre>";

/* This will output..

Array
(
    [0] => A
    [1] => w
    [2] => e
    [3] => s
    [4] => o
    [5] => m
    [6] => e
    [7] =>  
    [8] => w
    [9] => o
    [10] => r
    [11] => l
    [12] => d
)
Array
(
    [0] => Awe
    [1] => som
    [2] => e w
    [3] => orl
    [4] => d
)

*/
?>

Return Values:

If the optional split_length parameter is specified, the returned array will be broken down into pieces with each being split_length in length, otherwise each piece will be one character in length.

FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (& only) array element.

Cheers,
JENSon.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *