PHP explode() Function: Syntax, Parameters, Return Values, and Examples
This article explains PHP's explode() function, detailing its syntax, parameter descriptions, return values, edge cases such as empty delimiters and limit behavior, and provides multiple code examples demonstrating string splitting with various delimiters and limit settings.
PHP's explode() function splits a string into an array using a specified delimiter.
Signature: array explode(string $delimiter, string $string [, int $limit]) . The $delimiter defines the boundary characters, $string is the input, and $limit controls the maximum number of elements: a positive limit caps the array size, a negative limit excludes the last -limit elements, and zero is treated as one.
If the delimiter is an empty string, the function returns FALSE . If the delimiter is not found and a negative limit is used, an empty array is returned; otherwise the original string is returned as a single‑element array.
Examples:
<?php
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
?>Using list() with explode() to assign variables:
<?php
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
?>Demonstrating the $limit parameter:
<?php
$str = "one|two|three|four";
print_r(explode("|", $str, 2)); // limit 2
print_r(explode("|", $str, -1)); // negative limit
?>These examples illustrate how explode() behaves with different delimiters and limit values, producing arrays of substrings as shown in the output sections.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.