PHP chunk_split() Function β Complete Guide with Examples
What is chunk_split() in PHP?
The chunk_split() function in PHP splits a string into smaller chunks and inserts a separator (default is a newline \r\n).
π Use cases:
- Formatting long strings for readability.
- Breaking text into fixed-length parts (e.g., Base64 encoding).
- Generating output-friendly formatted text.
Syntax of chunk_split()
string chunk_split(string $string, int $length = 76, string $separator = "\r\n")
πΉ Parameters:
$stringβ The input string.$lengthβ (Optional) The chunk size (default = 76 characters).$separatorβ (Optional) String inserted after each chunk (default ="\r\n").
πΉ Return Value:
- Returns the formatted string with chunks separated by the given separator.
Example: Splitting a String into Chunks
<?php
$text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$chunked_text = chunk_split($text, 5, "-");
echo $chunked_text;
?>
β Output:
ABCDE-
FGHIJ-
KLMNO-
PQRST-
UVWXY-
Z- π How it works?
- The input string
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"is split into chunks of 5 characters. - A hyphen (
-) is added after each chunk.
Example: Splitting a Base64-Encoded String
<?php
$data = base64_encode("Hello, PHP chunk_split!");
$formatted = chunk_split($data, 4, " ");
echo $formatted;
?>
β Output:
SGVs IG8s IFBI UCBj dW5r X3Nw bGl0 ISE= π Why use chunk_split() here?
- Base64-encoded data often needs fixed-length formatting for readability.
Example: Formatting Credit Card Numbers
<?php
$card_number = "1234567812345678";
$formatted = chunk_split($card_number, 4, " ");
echo $formatted;
?>
β Output:
1234 5678 1234 5678 π Why use chunk_split() here?
- It formats credit card numbers for better readability.
Handling Edge Cases
πΉ What happens if the length exceeds the string size?
<?php
$text = "Hello";
echo chunk_split($text, 10, "-");
?>
β Output:
Hello- πΉ What if the separator is an empty string?
<?php
$text = "HelloWorld";
echo chunk_split($text, 3, "");
?>
β Output:
Hel loW
orl
d π Best practice: Always specify a meaningful separator to avoid unexpected formatting.
Best Practices for Using chunk_split()
β 1. Use for Readability
- Use
chunk_split()for breaking long text into readable parts (e.g., Base64, credit cards).
β 2. Handle Edge Cases
- If the string is shorter than
$length,chunk_split()adds a separator at the end.
β 3. Avoid Unnecessary Use
- If you need an array of chunks, consider
str_split()instead:
Β
<?php
print_r(str_split("HelloWorld", 3));
?>Array ( [0] => Hel [1] => loW [2] => orl [3] => d )
π Use str_split() when you need an array instead of a formatted string.
When to Use chunk_split()
π Use chunk_split() when:
β
You need formatted output (e.g., Base64 encoding, credit card numbers).
β
You want to insert separators after a fixed number of characters.
β οΈ Avoid if:
β You need an array instead β use str_split().
β The formatting doesnβt require separators.