php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #62613 'explode' quirk
Submitted: 2012-07-19 20:24 UTC Modified: 2012-07-19 21:19 UTC
From: matthew at binaryrefined dot net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.4.4 OS: Win XP, SP3
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: matthew at binaryrefined dot net
New email:
PHP Version: OS:

 

 [2012-07-19 20:24 UTC] matthew at binaryrefined dot net
Description:
------------
When providing an empty source string to explode, it returns an array with a 
single, empty element.  Expected behavior was an empty array.

Test script:
---------------
<?php

$x = explode('|', '');  // '' would be a variable, and not intentionally empty.
print_r($x);

?>

Expected result:
----------------
Array ()

Actual result:
--------------
Array ( [0] => )

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-07-19 20:49 UTC] matthew at binaryrefined dot net
To block against this, I've had to do a boolean check against the variable before applying explode to ensure an empty source 
string will produce an empty array:

 if ($x)
 {
    $x = explode('|', $x);
 }
 else
 { ... }  // $x is empty, and if passed to explode, results in an array with a single, empty element.

I've been developing with PHP for ~10 years and I cannot ever remember having to do this with explode.  The more I think about 
it, the more I believe this may be a bug?

Thanks for the time.
 [2012-07-19 21:19 UTC] bjori@php.net
-Status: Open +Status: Not a bug
 [2012-07-19 21:19 UTC] bjori@php.net
Why would it be empty?

explode() creates an new array, finds the first element of $delimiter chops it 
away and pushes the element to the array.
Then continues until there are no more instances of $delimiter, then pushes the 
last string to the return array...


Which means.. If there are no hits of the $delimiter, you'll just get the same 
string.. in an array of one element.. the same original string.

Why should empty argument have an special treatment? o.O
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 15:01:34 2025 UTC