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.
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.str_split(string, length) returns an array.chunk_split(string, length, separator) returns a formatted string.
// Splitting a string into chunks of 3 characters
The string "abcdefg" is divided into chunks of 3 characters. The last chunk contains the remaining character.
// Splitting a string into chunks of 2 characters with a separator
The string is split into 2-character chunks and a hyphen is added after each chunk.
// 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
str_split() when array output is required.chunk_split() for display-friendly formatting.chunk_split().