chunk_split()
The chunk_split() function is used to split a string into smaller chunks. The syntax of the chunk_split() function is as follows:
The PHP syntax of the chunk_split()
string chunk_split ( string $str [, int $chunklen = 76 [, string $end = "\r\n" ]] )The function takes up to three parameters: the string to be split ($str), the length of each chunk ($chunklen), and the string to append to each chunk ($end). The chunk_split() function returns the modified string.
Here is an example of how to use the chunk_split() function:
Example of PHP chunk_split()
<?php
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla at nulla justo, eget luctus tortor. Maecenas vel est at massa aliquam semper.";
$chunked_string = chunk_split($string, 20);
echo $chunked_string;
?>In this example, we have a long string that we want to split into smaller chunks of 20 characters. We pass the string and the chunk length to the chunk_split() function, which returns the modified string.
The output of this code will be:
Lorem ipsum dolor si
t amet, consectetu
r adipiscing elit. N
ulla at nulla justo,
eget luctus tortor
. Maecenas vel est a
t massa aliquam semp
er.As you can see, the chunk_split() function has split the long string into smaller chunks of 20 characters.
Here is another example of how to use the chunk_split() function with a different end string:
How to use PHP chunk_split()?
<?php
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla at nulla justo, eget luctus tortor. Maecenas vel est at massa aliquam semper.";
$chunked_string = chunk_split($string, 20, "\n");
echo $chunked_string;
?>In this example, we want to use a newline character ("\n") as the string to append to each chunk. We pass the string, chunk length, and end string to the chunk_split() function, which returns the modified string.
The output of this code will be:
Lorem ipsum dolor si
t amet, consectetu
r adipiscing elit. N
ulla at nulla justo,
eget luctus tortor
. Maecenas vel est a
t massa aliquam semp
er.As you can see, the chunk_split() function has split the long string into smaller chunks of 20 characters and appended a newline character to each chunk.
The chunk_split() function is a useful tool for splitting long strings into smaller chunks. It can help make your code more manageable and efficient. By mastering this function, you can become a more proficient PHP developer.
Practice
Which of the following descriptions offers correct information about the chunk_split() function in PHP?