Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.
Hello Friends Today, through this tutorial, I will tell you How to Use `str_split()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP 8.1 and 8.2, the `str_split()` function is used to split a string into an array of substrings, each containing a specified number of characters. Here’s how you can use `str_split()` along with an example:
Syntax:
<?php array str_split ( string $string [, int $split_length = 1 ] ) ?>
Parameters:
1. `$string`: The input string to split.
2. `$split_length`: (Optional) The maximum length of each substring. Default is 1.
Return Value: An array of substrings.
Example:
<?php // Example 1: Splitting a string into an array of characters $string = "Hello, world!"; $characters = str_split($string); print_r($characters); // Example 2: Splitting a string into an array of substrings with a specified length $string = "1234567890"; $chunks = str_split($string, 3); print_r($chunks); ?>
Output:
// Example 1 output: Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => , [6] => [7] => w [8] => o [9] => r [10] => l [11] => d [12] => ! ) // Example 2 output: Array ( [0] => 123 [1] => 456 [2] => 789 [3] => 0 )
In Example 1, the input string “Hello, world!” is split into an array of characters, with each character becoming an element of the resulting array.
In Example 2, the input string “1234567890” is split into an array of substrings, each containing 3 characters (except the last substring, which contains only one character).