PHP chunk_split() Function – Complete Guide with Examples
What is chunk_split() in PHP?
The PHP chunk_split() function is used to split a string into smaller chunks of a specified length. It is especially useful when formatting long strings, such as preparing text for emails.
If you want to break long text into readable parts, this function is very helpful.
What is chunk_split() in PHP?
The chunk_split() function divides a string into smaller pieces and optionally adds a separator at the end of each chunk.
Simple idea:
Long string → smaller chunks → formatted output
Syntax of chunk_split()
string chunk_split(string $string, int $length = 76, string $separator = "\r\n")
Parameters Explained
| Parameter | Description |
|---|---|
$string | Input string |
$length | Length of each chunk (default: 76) |
$separator | String added after each chunk |
Return Value
- Returns a formatted string
- Adds separator after each chunk
Basic Example
<?php
$text = "HelloWorldPHP";
$result = chunk_split($text, 5);
echo $result;
?>Output
World
PHP
Explanation
- Splits string every 5 characters
- Adds new line (
\r\n) automatically
Example with Custom Separator
<?php
$text = "ABCDEFGHIJK";
$result = chunk_split($text, 3, "-");
echo $result;
?>Output
Explanation
- Each chunk is 3 characters
-is added after each chunk
Real-World Use Cases
Real-World Use Cases
$message = chunk_split($longText, 70);Helps format long email lines
Formatting Output for Display
Output: 12 34 56 78 90
Splitting Serial Codes
echo chunk_split($code, 4, “-“);
Output:
Common Mistakes to Avoid
Confusing with explode()
❌ Wrong:
chunk_split()→ splits by lengthexplode()→ splits by delimiter
Unexpected Extra Separator
Output: A-B-C-
- at the endUsing for Arrays
Wrong: chunk_split($array);
Best Practices for Using chunk_split()
- Use appropriate chunk size
- Be aware of trailing separator
- Combine with
trim()if needed - Use for formatting, not data splitting
chunk_split() vs explode()
| Feature | chunk_split() | explode() |
|---|---|---|
| Type | String → String | String → Array |
| Based on | Length | Delimiter |
| Output | Formatted string | Array |
| Use Case | Formatting | Data parsing |
Advanced Example
<?php
$text = "ABCDEFGHIJK";
$result = chunk_split($text, 3, "-");
// Remove last separator
$result = rtrim($result, "-");
echo $result;
?>Output
Explanation
chunk_split()adds extra separatorrtrim()removes it
FAQs
What does chunk_split() do in PHP?
It splits a string into smaller chunks and adds a separator.
What is default chunk size?
76 characters.
Can I change separator?
Yes, using third parameter.
Why is there an extra separator at end?
Because function appends separator after every chunk.
What is alternative to chunk_split()?
Use loops or str_split() for more control.