0

String splitting and joining: explode, implode, str_split, chunk_split

Beginner5 min read·php-03-013

Concept

Splitting and joining strings are among the most common string operations. PHP provides multiple functions for these tasks, each with different performance characteristics and use cases.

explode($separator, $string, $limit) splits a string by a literal delimiter. Returns an array. $limit positive: maximum number of elements (last element contains the remainder). $limit negative: returns all elements except the last -$limit elements. $limit of 0 is treated as 1. Returns an array with one element (the full string) if the separator is not found. Throws ValueError if separator is empty string (PHP 8+).

implode($separator, $array) (alias join) joins an array into a string. No limit, no offset. For large arrays, this is the efficient way to build strings — collect parts in an array, join once at the end rather than concatenating incrementally.

str_split($string, $length) splits a string into an array of chunks of $length bytes (default 1). Returns byte chunks, not character chunks — use mb_str_split for Unicode. Useful for processing fixed-width fields, credit card numbers, or base64 chunking.

chunk_split (covered in padding lesson) splits into fixed chunks and inserts a separator between each.

preg_split for pattern-based splitting (covered in regex lesson).

Code Example

php
<?php
declare(strict_types=1);

// explode — split CSV line
$csv = 'Alice,30,Engineer,New York';
$fields = explode(',', $csv);
[$name, $age, $role, $city] = $fields;
echo "$name is $age years old\n";

// Limit parameter
$path = '/usr/local/bin/php';
$parts = explode('/', $path, 3); // max 3 elements
// ['', 'usr', 'local/bin/php']  — last element contains remainder

// Negative limit — exclude last 2 elements
$parts = explode('/', trim($path, '/'), -1);
// ['usr', 'local', 'bin']  — excludes 'php'

// implode — build strings efficiently
$tags = ['php', 'laravel', 'backend'];
echo implode(', ', $tags);  // "php, laravel, backend"
echo implode('/', ['2024', '01', '15']); // "2024/01/15"

// SQL IN clause generation (parameterized in practice!)
$ids = [1, 2, 3, 4, 5];
$placeholders = implode(', ', array_fill(0, count($ids), '?'));
$sql = "SELECT * FROM users WHERE id IN ($placeholders)";

// str_split — fixed-width chunks
$binary = 'ABCDEF';
$bytes = str_split($binary, 2); // ['AB', 'CD', 'EF']

// Process credit card number
$card = '4111111111111111';
echo implode('-', str_split($card, 4)); // "4111-1111-1111-1111"

// mb_str_split — Unicode-safe (PHP 7.4+)
$emoji = '🌍🌎🌏';
print_r(str_split($emoji, 1));    // garbled — splits by byte
print_r(mb_str_split($emoji));    // ['🌍', '🌎', '🌏'] — correct

// Parse key=value format
$config = "host=localhost\nport=3306\ndbname=myapp";
$settings = [];
foreach (explode("\n", $config) as $line) {
    [$key, $value] = explode('=', $line, 2); // limit 2: value may contain =
    $settings[trim($key)] = trim($value);
}