PHP chunk_split is an inbuilt function in PHP. It splits the input string into smaller chunks of the specified length. In this article, we will discuss the PHP chunk_split Function. Also, we will discuss a few examples of using it.
string chunk_split($string, $length = 76, $end = “\r\n”)
The PHP chunk_split Function expects three parameters. However, only one parameter is mandatory and two are optional.
- $string: The first parameter to the function is the input string. It is a mandatory parameter.
- $length: The second parameter specifies the length of each chunk. It is an optional parameter with default value as 76.
- $end: The third parameter to the function specifies the line ending sequence. Also, it is an optional parameter.
The PHP chunk_split returns a string after dividing it in smaller chunks.
Let’s discuss a few examples of using the function.
Example 1: Simple Chunks
For instance, consider a splitting a simple string into smaller chunks.
<?php //Split the string into chunks of size 3 ending with * $inputString = 'Bringing Knowledge Together'; echo chunk_split($inputString, 3, '*'); ?>
In the above example, we split the string into chunks of size 3 ending with *.
OUTPUT: Bri*ngi*ng *Kno*wle*dge* To*get*her*
Example 2: Uneven Splitting
The last chunk is always ended with the $end string if the chunk size if uneven.
<?php $inputString = 'Bringing Knowledge Together'; echo chunk_split($inputString, 5, '##'); ?>
In the above example, the string is split into smaller chunks of length 5. However, the last chunk contains only 2 characters.
OUTPUT: Bring##ing K##nowle##dge T##ogeth##er##
Example 3: Chunk Size More than Original Length
If the chunk size is more than the original length of the string, then the function adds the $end string at the end.
<?php $inputString = 'ABC'; echo chunk_split($inputString, 5, '##'); ?>
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.