PHP str_split() Function

PHP str_split() function is “used to convert the string into an array.” 

Syntax

str_split($string, $length)

Parameters

  1. $string: This is an input string.
  2. $length: It specifies the length of each array element. The default is 1.

Return value

If the length is larger than the length of the string, the entire string will be returned as the only element of the array.

If the string is empty, an empty array will be returned(PHP 8.2.0).

Visual RepresentationVisual Representation of PHP str_split() Function

Example 1: How to Use str_split() Function

<?php

$str = "AppDividend";

print_r(str_split($str));

Output

Array
(
 [0] => A
 [1] => p
 [2] => p
 [3] => D
 [4] => i
 [5] => v
 [6] => i
 [7] => d
 [8] => e
 [9] => n
 [10] => d
)

Example 2: Using length parameterVisual Representation of Using length parameter

<?php

$str = "AppDividend";

print_r(str_split($str,4));

Output

Array
(
 [0] => AppD
 [1] => ivid
 [2] => end
)

In the above example, the string is split into chunks of four characters each, except for the last element which contains the remaining characters.

Example 3: Empty stringVisual Representation of Empty string

<?php

$str = "";

print_r(str_split($str));

Output

Array
(
 [0] => 
)

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.