PHP chunk_split() Function

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Functions

What You’ll Learn

The chunk_split() function splits a string into fixed-size pieces and inserts a separator after each piece. It returns one formatted string—perfect for wrapping long lines in email bodies, displaying hex data, or breaking text into readable blocks.

01

Fixed Chunks

Set max chunk length.

02

Custom Separator

Dash, space, or newline.

03

Default 76

MIME/email convention.

04

Returns String

Not an array.

05

Last Chunk

May be shorter.

06

vs str_split()

Formatted vs array.

Definition and Usage

In PHP, chunk_split() walks through a string from left to right, taking $length characters at a time and appending the $separator after each group. For example, splitting "HelloWorld123" into chunks of 4 with "-" produces Hell-oWor-ld12-3-.

💡
Beginner Tip

The separator is added after every chunk, including the last one—so the result often ends with the separator character. If you need an array of pieces without separators, use str_split() instead.

📝 Syntax

The chunk_split() function accepts up to three parameters:

PHP
string chunk_split(string $string, int $length = 76, string $separator = "\r\n")

Parameters

  • $string — the input string to split into chunks.
  • $length (optional) — maximum characters per chunk. Default: 76.
  • $separator (optional) — string inserted after each chunk. Default: "\r\n" (carriage return + line feed).

Return Value

Returns a new string with chunks and separators combined. The original string is not modified.

⚡ Quick Reference

InputCallResult
"HelloWorld123"chunk_split($s, 4, "-")Hell-oWor-ld12-3-
"ABCDEFGH"chunk_split($s, 3, " ")ABC DEF GH
"1234567890"chunk_split($s, 4, "|")1234|5678|90|
"Hi"chunk_split($s, 5, "-")Hi- (one short chunk)
""chunk_split($s, 4, "-")""
Basic
chunk_split($s, 4, "-")

4-char chunks with dashes

Default
chunk_split($s)

76 chars + \r\n

Array
str_split($s, 4)

Chunks as array

Trim tail
rtrim(chunk_split($s,4,"-"), "-")

Remove trailing sep

Examples Gallery

Run these examples in any PHP 7+ environment. Each one demonstrates a common pattern beginners encounter with chunk_split().

📚 Getting Started

Split a string into fixed-size chunks with a custom separator.

Example 1 — Chunks with a Dash Separator

The classic beginner example: break a string into groups of four characters separated by dashes.

PHP
<?php
$input       = "HelloWorld123";
$chunked     = chunk_split($input, 4, "-");

echo $chunked . "\n";
echo "Length: " . strlen($chunked) . "\n";
?>

How It Works

  • Chunk 1: Hell, chunk 2: oWor, chunk 3: ld12, chunk 4: 3 (only 1 char).
  • A dash is appended after each chunk, including the final 3.
  • Original 13 characters become 17 with four separators added.

Example 2 — Default MIME-Style Line Wrapping

Calling chunk_split() with only the string uses 76-character lines and \r\n line breaks—the classic email encoding format.

PHP
<?php
$data = str_repeat("A", 80);  // 80-character string
$wrapped = chunk_split($data);

$lines = explode("\r\n", trim($wrapped));
echo "Total lines: " . count($lines) . "\n";
echo "Line 1 length: " . strlen($lines[0]) . "\n";
echo "Line 2 length: " . strlen($lines[1]) . "\n";
?>

How It Works

80 characters split at 76: first line has 76 A’s, second line has the remaining 4. This is why Base64 email attachments often use chunk_split(base64_encode($data)).

📈 Practical Patterns

Formatting and comparison patterns for real PHP code.

Example 3 — Display Credit Card–Style Groups

Make long digit strings readable by inserting spaces every four characters.

PHP
<?php
$cardNumber = "4111111111111111";
$display    = rtrim(chunk_split($cardNumber, 4, " "), " ");

echo $display . "\n";
?>

How It Works

chunk_split() adds a trailing space after the last group. Wrapping with rtrim(..., " ") removes that final space for clean display output.

Example 4 — chunk_split() vs str_split()

See the difference between a formatted string and an array of chunks.

PHP
<?php
$text = "PHP8Rock";

echo "chunk_split:\n";
echo chunk_split($text, 3, "|") . "\n";

echo "str_split:\n";
print_r(str_split($text, 3));
?>

How It Works

chunk_split() builds one string with separators baked in. str_split() gives you an array so you can loop, validate, or join chunks your own way.

Example 5 — Formatting a Long Hex String

Pair bin2hex() with chunk_split() to display binary data in readable blocks.

PHP
<?php
$raw  = "CodeToFun";
$hex  = bin2hex($raw);
$pretty = rtrim(chunk_split($hex, 8, " "), " ");

echo "Raw:    $raw\n";
echo "Hex:    $hex\n";
echo "Pretty: $pretty\n";
?>

How It Works

Each 8-character hex block represents 4 bytes. Spacing makes long hashes and dumps easier to read in logs or debug output.

🚀 Common Use Cases

  • MIME email encoding — wrap Base64 attachment data at 76 characters per line.
  • Readable number groups — format long IDs, phone numbers, or card numbers for display.
  • Hex and hash output — space-separate long hexadecimal strings in debug logs.
  • Protocol formatting — insert line breaks in fixed-width text payloads.
  • Teaching string manipulation — understand chunking before learning arrays and loops.

🧠 How chunk_split() Works

1

PHP reads the input string

You provide the string, chunk length, and separator (or rely on defaults 76 and \r\n).

Input
2

String is cut into pieces

PHP takes up to $length characters per chunk, left to right. The final piece may contain fewer characters.

Transform
3

Separators are inserted

After each chunk—including the last—PHP appends the separator string and concatenates everything.

Output
=

Formatted string

One string ready to echo, email, or log—with chunks visually separated.

📝 Notes

  • The separator is appended after every chunk, including the last partial one.
  • Use rtrim($result, $separator) if you need to remove a trailing separator.
  • Default length 76 and separator \r\n target email/MIME compatibility.
  • For an array of chunks, use str_split($string, $length) instead.
  • Chunk length must be at least 1; passing 0 or negative values causes errors in PHP 8+.

Conclusion

The chunk_split() function is a straightforward way to break long strings into fixed-size segments with separators between them. From MIME email wrapping to readable number formatting, it returns a single formatted string in one function call.

Remember the trailing separator behavior, know when to reach for str_split() instead, and use rtrim() when you need a clean final result without extra characters at the end.

💡 Best Practices

✅ Do

  • Use defaults for MIME/Base64 email line wrapping
  • Trim trailing separators when displaying to users
  • Use str_split() when you need to process chunks in a loop
  • Pick chunk sizes that match your display or protocol requirements
  • Test with strings whose length is not divisible by chunk size

❌ Don’t

  • Expect chunk_split() to return an array
  • Forget the trailing separator on the last chunk
  • Use chunk_split() for word-aware wrapping (use wordwrap() instead)
  • Pass zero or negative chunk lengths
  • Assume chunks split on word boundaries

Key Takeaways

Knowledge Unlocked

Five things to remember about chunk_split()

Use these points whenever you format strings in fixed-size blocks.

5
Core concepts
🔄 02

Returns String

Not an array.

Behavior
🛠 03

Default 76

MIME line length.

Syntax
📧 04

Email / Base64

Classic use case.

Use case
05

vs str_split()

Formatted vs array.

Compare

❓ Frequently Asked Questions

chunk_split() breaks a string into fixed-size pieces and inserts a separator after each piece. It returns one combined string—not an array. The last chunk may be shorter than the requested length, and the separator is still appended after it.
string chunk_split(string $string, int $length = 76, string $separator = "\r\n"). You pass the input string, the maximum chunk size (default 76), and the separator string appended after every chunk (default carriage return + line feed).
That is by design. Every chunk—including the final partial one—is followed by the separator. If you do not want a trailing separator, trim it afterward or use str_split() and implode() for more control.
chunk_split() returns a single string with separators inserted between chunks. str_split() returns an array of chunk strings with no separator added. Use chunk_split() for formatted output; use str_split() when you need to process chunks individually.
76 characters per line is a long-standing convention for email and MIME-encoded content (such as Base64 bodies). The default separator "\r\n" matches Windows-style line endings used in many mail formats.
The final chunk contains whatever characters remain—they are not padded. A separator is still added after that shorter last chunk.

Explore More PHP String Functions

Continue with count_chars(), explode(), and the rest of the string function reference.

Next: convert_cyr_string() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful