How to Use chunk_split() Function in PHP 8.1 and 8.2 with Example?

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 `chunk_split()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. In PHP 8.1 and 8.2, the `chunk_split()` function is used to split a string into smaller chunks of a specified length and insert a delimiter between each chunk. Here’s how you can use it with examples:

Syntax:

<?php
chunk_split(string $string, int $length = 76, string $end = "\r\n"): string
?>

Parameters:

1. `$string`: The input string to be split into chunks.
2. `$length` (Optional): The length of each chunk. Default is 76 characters.
3. `$end` (Optional): The string to be appended to the end of each chunk. Default is “\r\n” (CRLF).

Example 1: Basic Usage

<?php
$inputString = "HelloWorldThisIsALongString";
$chunkedString = chunk_split($inputString, 5);
echo $chunkedString;
?>

Output:

Hello
World
ThisI
sALon
gStri
ng

Example 2: Specifying Chunk Length and End of Line

<?php
$inputString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$chunkedString = chunk_split($inputString, 10, "\n");
echo $chunkedString;
?>

Output:

Lorem ipsu
m dolor si
t amet, co
nsectetur
adipiscin
g elit.

In these examples, the `chunk_split()` function divides the input string into smaller chunks of specified length (`$length`) and inserts the delimiter (`$end`) between each chunk. It returns the chunked string as output.