Code has been added to clipboard!

PHP explode()

Reading time 1 min
Published Aug 14, 2017
Updated Oct 10, 2019

PHP explode: Main Tips

  • PHP explode function is used to get an array of strings from a single string.
  • Using explode() in PHP is completely binary-safe.
  • It was introduced in PHP4 with the limit parameter, though negative limits weren't allowed until PHP 5.1.

Syntax: Parameters Explained

The correct PHP explode function syntax is displayed below:

explode(separator,string,limit);

Let's figure out what each parameter represents when using PHP explode function:

Parameter Description
separator Needed. Defines the place where should PHP explode string. Cannot be an empty string!
string Needed. Specifies the exact string to split.
limit Optional. Defines the number of elements in an array to return after:
> 0 - Returns the array including a max of limit element(s)
< 0 - Returns the array except for the last -limit elements()
0 - Returns an array with one element

Usage: Code Examples

Look at the example below. It shows different outcomes that can be achieved using limit parameter with PHP explode function:

Example
<?php
  $string = 'first,second,third,fourth';

  // limit - zero
  print_r(explode(',', $string, 0));

  // limit - positive
  print_r(explode(',', $string, 2));

  // limit  - negative
  print_r(explode(',', $string, -1));
?>

In this next example, comma is used as a separator. See how that turns out:

Example
<?php
  $string = "This is example, with, commas!";
  print_r (explode(",", $string));
?>
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()