AppDividend
Latest Code Tutorials

PHP str_split: How to Split a String in PHP

The str_split() function splits the given string into smaller strings of the length specified by a user, stores them in the array, and returns an array.

PHP str_split()

PHP str_split() is a built-in function that splits a string into an array. To convert a string to an array in PHP, use the str_split() function. The str_split() function takes two arguments and returns an array with split string as individual elements.

Syntax

The syntax of the str_split() method is the following.

str_split(string, length)

Parameters

The string parameter is required, and it specifies the string to split.

The length parameter is optional, and it specifies the length of each array element. The default is 1.

See the following code example.

<?php
print_r(str_split("Millie Bobby Brown", 6));

See the output.

➜  pro php app.php
Array
(
    [0] => Millie
    [1] =>  Bobby
    [2] =>  Brown
)
➜  pro

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

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

The str_split() will split into bytes rather than characters when dealing with a multi-byte encoded string.

If the split_length length exceeds the length of the string, the entire string is returned as the first (and only) array element.

See another example.

<?php

print_r(str_split("KRUNAL"));

See the output.

➜  pro php app.php
Array
(
    [0] => K
    [1] => R
    [2] => U
    [3] => N
    [4] => A
    [5] => L
)
➜  pro

That’s it for this tutorial.

Recommended Posts

PHP str_repeat()

PHP Functions

PHP chunk_split()

PHP count_chars()

PHP chop()

PHP money_format()

Leave A Reply

Your email address will not be published.

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