Content · Programming · PHP

PHP chunk_split() Function: Usage and Examples

Learn how PHP chunk_split works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Splits a string into chunks and inserts a chosen separator.

What Is chunk_split() in PHP?

Splits a string into chunks and inserts a chosen separator.

Its syntax is:

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

Parameters:

  • $string — Accepted as string; required argument.
  • $length — Accepted as int; optional default 76.
  • $separator — Accepted as string; optional default "\r\n".

Return type: string. The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.

Availability: Core PHP.

Example 1: Basic Usage

<?php

echo chunk_split("ABCDEFGHIJ", 4, "|");

Output:

ABCD|EFGH|IJ|

The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.

Example 2: A Different Input

<?php

echo chunk_split("123456", 3, "-");

Output:

123-456-

The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.

Practical Example: Applying It in a Program

<?php

$encodedData = base64_encode("Sample attachment content"); echo chunk_split($encodedData, 8, "\n");

Output:

U2FtcGxl
IGF0dGFj
aG1lbnQg
Y29udGVu
dA==

The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.

Important Behavior and Edge Cases

  • Key behavior: The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.
  • Environment: Core PHP.

Comparison With Related Functions

FunctionPurpose
chunk_split()Splits a string into chunks and inserts a chosen separator.
str_split()str_split() returns an array of pieces; chunk_split() returns a string with separators between chunks.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: The separator is appended after each chunk, including the final chunkThe separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.

Key Takeaways

  • Splits a string into chunks and inserts a chosen separator.
  • The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.
  • Core PHP.

Summary: The separator is appended after each chunk, including the final chunk. Not suitable for splitting Unicode characters.

Share this resourceSend this page to someone who may find it useful.