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.