PHP Function Reference

PHP str_split() Function



The PHP str_split() function splits a string into an array. This function has an optional parameter which is used to specify the number of characters for each split with default value 1. Please note that it does not change the original string.

Syntax

str_split(string, length)

Parameters

string Required. Specify the string to split
length Optional. Specify length of each element of the array. Default is 1.

Return Value

Returns the array containing split string as elements of the array.

Example:

In the example below, str_split() function is used to split a string into an array with specified element length.

<?php
$str = "Hello World!";

//splitting the string with length=1
$arr1 = str_split($str);
print_r($arr1);

echo "\n";

//splitting the string with length=3
$arr2 = str_split($str,3);
print_r($arr2);
?>

The output of the above code will be:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>  
    [6] => W
    [7] => o
    [8] => r
    [9] => l
    [10] => d
    [11] => !
)

Array
(
    [0] => Hel
    [1] => lo 
    [2] => Wor
    [3] => ld!
)

❮ PHP String Reference