← Back to Chapters

PHP str_split() & chunk_split()

? PHP str_split() & chunk_split()

? Quick Overview

PHP provides useful functions to manipulate strings in chunks: str_split() and chunk_split(). These functions allow you to divide a string into smaller parts, which can be useful for tasks such as formatting text or processing strings in manageable segments.

? Key Concepts

  • str_split() – Splits a string into an array of smaller chunks of a specified length.
  • chunk_split() – Breaks a string into smaller chunks and optionally adds a separator between each chunk.

? Syntax & Theory

  • str_split(string, length) returns an array.
  • chunk_split(string, length, separator) returns a formatted string.

? Code Example: str_split()

? View Code Example
// Splitting a string into chunks of 3 characters

? Explanation

The string "abcdefg" is divided into chunks of 3 characters. The last chunk contains the remaining character.

? Code Example: chunk_split()

? View Code Example
// Splitting a string into chunks of 2 characters with a separator

? Explanation

The string is split into 2-character chunks and a hyphen is added after each chunk.

? Interactive Visualization

? View Demo Logic
// Simulating PHP chunking logic using JavaScript
const text = "HELLOWORLD";
const size = 3;
let result = [];
for (let i = 0; i < text.length; i += size) {
result.push(text.substring(i, i + size));
}
console.log(result);

Result: HEL / LOW / ORL / D

? Use Cases

  • Formatting long strings like credit card numbers.
  • Breaking data for transmission.
  • Processing text in fixed-size blocks.

✅ Tips & Best Practices

  • Use str_split() when array output is required.
  • Use chunk_split() for display-friendly formatting.
  • Be mindful of trailing separators.

? Try It Yourself

  • Split a sentence into chunks of 4 characters.
  • Format a phone number using chunk_split().
  • Experiment with large strings and different separators.