Use Code: BFCM24 to get 58% OFF your annual membership. Expires soon 👇

Beginner's Guide to PHP explode() Function (With Code Examples!)

Luis Ramirez Jr
Luis Ramirez Jr
hero image

At first glance, explode() may seem like just another PHP function, but did you know that it's a secret weapon for parsing strings and manipulating data?

With explode(), you can easily:

  • Break down a string into manageable chunks
  • Make sense of CSV data
  • And make your life as a developer much easier!

Not sure how to use it?

Well, good news! In this guide, we’ll be exploring what explode() really is and why you should use it.

Then, I'll delve into how it works, its parameters, and its usage. Finally, once you've mastered the basics, we’ll take a look at handling different delimiters, best practices with these, as well as how to use explode() with a $limit parameter, and processing CSV data!

By the time you finish reading this guide, not only will your PHP skills be that much sharper, but you'll also be equipped with the knowledge to tackle real-world data manipulation tasks with greater efficiency.

Ready? Alright, let’s dive in!

What is the PHP explode function and how does it work?

As you well know if you’re reading this guide, PHP, or ‘Hypertext Preprocessor’, is a widely-used open-source scripting language especially suited for web development. It's embedded into HTML and is especially useful for tasks like data manipulation and dynamic content creation.

explode() is one of the ways that we can manipulate that data. It’s a built-in function that is primarily used to split a string into an array.

It works like this:

  • It takes a string and a delimiter as inputs
  • The function then breaks the input string at each instance of the delimiter, resulting in an array of substrings

Why use explode?

The explode() function is extremely useful in various programming scenarios where you need to process or analyze parts of a string separately.

For example:

  • Parsing CSV Data: You can use explode() to split a line of CSV data into individual fields
  • Analyzing Log Files: It helps in breaking down log file entries into their components for easier analysis
  • Data Processing: Whenever you need to split a string into manageable chunks in your PHP script, explode() is the function to use

I’ll cover some examples of this in action in just a second, but first, let’s take a deeper look at the syntax.

Understanding the explode syntax

The general syntax of the explode() function is:

$array = explode(separator, string, limit);

As you can see from the code, the explode() function takes up to three parameters:

  1. separator: The character or string used to split the input string
  2. string: The input string that you want to split
  3. limit (optional): Limits the number of splits

How does explode work?

The explode() function works by splitting the input string at every instance of the specified delimiter. The resulting pieces are then returned as an array, with index numbers starting from 0.

Here are some examples to help visualize this a little easier

Example 1: Splitting by a comma

This is particularly useful when dealing with CSV (Comma-Separated Values) data, where each piece of data is separated by a comma.

Input:

<?php
$inputString = "Hello, how, are, you?";
print_r(explode(",", $inputString));
?>

Output:

Array
(
	[0] => Hello
	[1] => how
	[2] => are
	[3] => you?
)

Example 2: Splitting by a hyphen

This can be useful in scenarios where data fields are separated by hyphens, such as in certain types of formatted text or identifiers (e.g., social security numbers, phone numbers).

Input:

<?php
$inputString = "one-two-three-four-five";
print_r(explode("-", $inputString));
?>

Output:

Array
(
	[0] => one
	[1] => two
	[2] => three
	[3] => four
	[4] => five
)

Example 3: Using explode() without the limit parameter

This example splits a string of fruit names separated by commas followed by spaces.

This is useful for splitting a list of items, such as ingredients in a recipe or elements in a list, into an array for easier processing and manipulation.

Input:

<?php
$inputString = "apple, banana, cherry, date, elderberry";
print_r(explode(", ", $inputString));
?>

Output:

Array
(
	[0] => apple
	[1] => banana
	[2] => cherry
	[3] => date
	[4] => elderberry
)

Understanding delimiters in PHP explode

As you can see, delimiters act as a boundary marker within the input string, indicating where the divisions should occur.

So far we’ve looked at using commas, hyphens, and commas with a space after them.

However, the delimiter you choose for the explode() function can be any character or sequence of characters. It’s completely up to you what you decide to use, and depends on what you're trying to achieve with your script.

For example

You could use a space on its own as a delimiter to split a sentence into individual words:

Input:

<?php
$inputString = "The quick brown fox jumps over the lazy dog";
print_r(explode(" ", $inputString));
?>

This script would output an array where each word of the sentence forms an element of the array.

Output:

Array
(
	[0] => The
	[1] => quick
	[2] => brown
	[3] => fox
	[4] => jumps
	[5] => over
	[6] => the
	[7] => lazy
	[8] => dog
)

In this case, every instance of a space character is where the string gets split into substrings.

Why would we use this delimiter option?

Well, by using a space as a delimiter to break up words in a sentence can help if we want to run natural language processing or other tasks.

For example:

  • Text Analysis: When analyzing text data, you might want to count the frequency of each word in a sentence or document. Splitting the sentence into individual words makes it easier to perform this analysis
  • Search Functionality: In search algorithms, breaking a sentence into words allows you to match individual terms against a search query
  • User Input Processing: When processing user input, such as a search bar or a form, splitting the input string into separate words can help in parsing and understanding the user's intent
  • Keyword Extraction: If you're developing a feature that extracts keywords from text, splitting the text into individual words is a necessary step

TL;DR

You can choose whatever delimiter you want, with some being better options than others. This is why you just need to be careful how you use them…

Best practices for using the PHP explode function

Here are a few best practices to keep in mind:

  • Check if the delimiter exists: First off, always check if the delimiter you're using exists in the string. If it doesn't, explode() will return an array with one element that is the entire string 😢
  • Handle special characters carefully: Be careful when using special characters as delimiters as they might not work as expected. Always test your code thoroughly just in case
  • Check the return type: explode() returns an array, so ensure that your code is equipped to handle an array response

For example

Here we can see some code that illustrates these best practices:

<?php
$inputString = "Hello there! Are you enjoying PHP yet?";
$delimiter = " ";
// ensure delimiter exists in string
if (strpos($inputString, $delimiter) === false) {
	echo "Delimiter not found in string";
} else {
	$resultArray = explode($delimiter, $inputString);
	if (is_array($resultArray)) {
    	print_r($resultArray);
	} else {
    	echo "Error: Expected an array from explode()";
	}
}
?>

This script checks if the delimiter exists in the string, and only then does it proceed with the explode() function. Not only that, but it also checks if the result of explode() is an array before trying to print it out.

Simple!

So with those best practices and basics out of the way, let’s look at some more specific examples.

Example #1. How to use the PHP explode function with a $limit parameter

As I mentioned earlier, the explode() function can also take an optional third argument, limit, so let’s take a look at this in action.

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of the string.

For example

Let's say we want to split a string but only want the first two elements in the array:

Input:

<?php
$inputString = "apple, banana, cherry, date, elderberry";
print_r(explode(", ", $inputString, 2));
?>

This will return:

Output:

Array
(
	[0] => apple
	[1] => banana, cherry, date, elderberry
)

So what's happening here?

Well in this example, the explode function only splits the string twice.

The first split happens at the first instance of the delimiter (comma followed by a space), and the rest of the string is included as the second element of the array.

Using the $limit parameter with the explode() function is particularly useful in scenarios where you want to split a string into a fixed number of parts, ensuring that the remaining part of the string is kept intact.

Here are a few practical applications for using this option:

  • Parsing Complex Data Structures: When dealing with complex data structures, you might need to split a string into key-value pairs, with the value containing additional delimiter-separated data. For example, parsing a configuration line like "key1: value1, value2, value3", where you want to separate the key from the values but keep the values together
  • User Input Processing: If you're processing user input where the first few elements are significant, but the remaining input needs to be considered as a single unit. For instance, splitting an address string where the first part is the street name and the second part is the rest of the address
  • Log File Analysis: When analyzing log files, you might want to split the log entry into the initial important parts (like timestamp and log level) while keeping the rest of the log message intact for further processing

Example #2. Using the PHP explode function with a negative $limit parameter

The explode() function can also take a negative $limit parameter.

When using a negative limit, the returned array will exclude the specified number of elements from the end of the string. Let's see this in action.

For example, using -2 as the limit will exclude the last two elements:

Input:

<?php
$inputString = "apple, banana, cherry, date, elderberry";
print_r(explode(", ", $inputString, -2));
?>

This will return:

Output:

Array
(
	[0] => apple
	[1] => banana
	[2] => cherry
)

So what's happening here?

In this example, the explode function splits the string and returns an array excluding the last two elements.

The first split happens at the first instance of the delimiter (comma followed by a space), and the resulting array contains all elements except for the last two.

Using a negative limit with the explode() function is particularly useful in scenarios where you want to exclude a certain number of trailing elements from the split result.

Here are a few practical applications:

  • Filtering Data: When you need to process only the initial part of a dataset and exclude the last few items, such as when analyzing a list of items but ignoring the last few entries because they are irrelevant or contain metadata
  • Log Analysis: In log analysis, you might want to focus on the initial parts of log entries and exclude specific trailing details that are less important or redundant
  • Processing Structured Text: When dealing with structured text data where the last few elements might be summary information or footer details that you want to exclude from the main processing

Example #3. Using the PHP explode function for processing CSV data

The explode() function is incredibly handy when it comes to processing CSV (Comma-Separated Value) data. (CSV is a simple file format used to store tabular data, such as a spreadsheet or database).

The explode() function makes it easy to parse this data and manipulate it in a PHP script.

Consider the following CSV data:

Name, Age, Occupation
John, 28, Engineer
Jane, 32, Doctor

You can use explode() to process this data like so:

<?php
// Open the CSV file
$file = fopen("example.csv", "r");

// Loop through each line in the file
while (($line = fgets($file)) !== false) {
	// Use explode() to split the line of text into an array
	$data = explode(", ", $line);

	// Now you can access each field in the CSV
	$name = $data[0];
	$age = $data[1];
	$occupation = $data[2];

	echo "Name: $name, Age: $age, Occupation: $occupation\n";
}

// Don't forget to close the file
fclose($file);
?>

Using the explode() function for processing CSV data is particularly useful in scenarios where you need to handle tabular data in a PHP script.

Here are a few practical applications:

  • Data Importing: When importing data from CSV files into a database or another data storage system, explode() can be used to split each line of the CSV file into individual fields for easier processing and insertion
  • Data Analysis: For analyzing CSV data, explode() allows you to break down each row into its constituent parts, making it easier to perform calculations, generate reports, or visualize data
  • Form Processing: If you receive CSV data from user uploads or external sources, explode() helps in parsing and validating the data before using it in your application
  • Configuration Files: CSV files are sometimes used for configuration settings. Using explode(), you can parse these files and apply the configurations dynamically in your PHP script

Example #4. Using the PHP explode function for parsing HTTP URLs

Handling paths in URLs is a common requirement in web development, especially when building applications that need to parse and route requests based on URL components.

Sidenote: It’s also something I cover and you learn touse in my PHP course. Being able to parse paths is something I do a lot in PHP applications, and I’m sure it’ll be useful for you to help determine what content should be rendered based on the path also.

The explode() function in PHP can be a powerful tool for breaking down the path portion of a URL into its individual segments, which can then be used for various purposes such as routing, resource identification, or logic execution based on the path structure.

For example

First, you need to extract the path component of the URL. PHP's parse_url() function is handy for this purpose, as it can parse a URL and return its components.

It's also a good practice to trim any leading or trailing slashes to ensure consistent results regardless of the input URL format. This can be done using the trim() function.

$url = "http://example.com/user/profile/edit";
$path = parse_url($url, PHP_URL_PATH);

$trimmedPath = trim($path, "/");

Once you have a normalized path, you can use explode() to split the string into an array of segments based on the slash (/) delimiter.

$segments = explode("/", $trimmedPath);
// $segments will be an array like ['user', 'profile', 'edit']

With the path broken into segments, you can use these segments for various tasks such as:

  • Routing in MVC Frameworks: Use the segments to determine which controller and method to invoke in an MVC (Model-View-Controller) framework
  • Access Control: Check if a user has permission to access certain parts of the path, enabling more granular security and access control in your application
  • Dynamic Content Serving: Dynamically serve different content or templates based on the path, allowing for flexible and scalable content management

Here’s a simple example of how you might use these segments to implement a basic routing mechanism:

switch ($segments[0]) {
	case "user":
    	if (isset($segments[1]) && $segments[1] == "profile") {
        	if (isset($segments[2]) && $segments[2] == "edit") {
            	// Code to display the edit profile page
            	echo "Edit User Profile Page";
        	} else {
            	// Code to display the user profile
            	echo "User Profile Page";
        	}
    	}
    	break;
	case "about":
    	// Code to display the about page
    	echo "About Page";
    	break;
	default:
    	// Code for a 404 not found page
    	echo "404 Not Found";
    	break;
}

Using the explode() function for parsing HTTP URLs is essential in web development for several reasons:

  • Routing Requests: In frameworks like Laravel or Symfony, URL routing is fundamental. By splitting the URL path into segments, you can map these segments to specific controllers and actions, enabling clean and maintainable routing logic
  • Resource Identification: URLs often contain identifiers for resources (e.g., /user/123/profile). Splitting the URL helps in extracting these identifiers and using them to fetch or manipulate the relevant resources
  • Custom URL Structures: If you are building a custom CMS or a web application that requires unique URL structures, parsing the URL into segments allows you to implement custom routing and handling logic

Tips and tricks for optimizing your usage of PHP

Just before we finish up, here are some final tips and tricks that you should be aware of when using the explode() function:

1. Be aware of empty strings

When your string starts or ends with a delimiter, explode() will include empty strings in the array, so always be sure to handle these cases appropriately in your code.

Input:

<?php
$string = ',Hello,,World,';
print_r(explode(',', $string));
?>

This script outputs:

Output:

Array
(
	[0] =>
	[1] => Hello
	[2] =>
	[3] => World
	[4] =>
)

In this example, there are empty strings in the positions where a delimiter was followed immediately by another delimiter, or at the start/end of the string.

Handling these empty strings is important when you need to ensure the integrity of the data being processed. For instance, if you are splitting a list of user inputs or log entries, you might want to ignore or clean up empty entries to avoid processing errors or data inconsistencies.

2. Use list() for simple cases

If you only need to split a string into a few variables, you can use list(), which will let you directly assign variables from an explode operation.

<?php
$string = 'Hello,World';
list($greeting, $object) = explode(',', $string);
echo $greeting; // Outputs: Hello
echo $object; // Outputs: World
?>

Using list() with explode() simplifies the assignment of split values to variables, making the code cleaner and more readable.

This is particularly useful when dealing with simple data structures, such as coordinates ("x,y") or pairs of values where you need direct access to the individual components.

3. Delimiters are case sensitive

explode() differentiates between upper-case and lower-case delimiters, so make sure that you always use the correct case in your delimiters to prevent unexpected results.

For example, if you are processing user input where the delimiter could be either "X" or "x", using the wrong case could lead to incorrect splits and data processing errors.

Always standardize your delimiters or handle both cases appropriately.

4. Use preg_split() for complex delimiters

If you need to split a string by complex delimiters or need to use regular expressions as delimiters, consider using preg_split() instead.

preg_split() allows for more complex and flexible delimited splitting.

Input:

$string = "one:two;three|four";
$pattern = "/[:;|]/";
print_r(preg_split($pattern, $string));
?>

This script outputs:

Output:

Array
(
	[0] => one
	[1] => two
	[2] => three
	[3] => four
)

preg_split() is helpful when dealing with strings that contain multiple or complex delimiters.

For example

Regular expressions provide powerful pattern-matching capabilities, making it easier to handle varied and intricate splitting criteria, so this option is particularly useful in data parsing, text processing, and situations where delimiters are not consistent or straightforward.

What's next?

The explode() function is an essential tool in any PHP developer's toolbox. With its ability to split strings by delimiters and its optional limit parameter, it provides a great way to parse and manage string data.

Hopefully, this guide has helped you get a better grasp of this function and given you a few ideas for how you can put this function to use in your own projects.

Because that’s the best way to learn, if you want it to stick!

While this guide covers the basics of using explode(), the best way to fully comprehend this is by practicing and experimenting with the function. Apply it to your PHP projects and see how it can enhance your code proficiency and efficiency.

P.S.

If you’ve enjoyed this guide and want to dive even deeper into PHP's more advanced features, or even want to learn PHP from scratch (perhaps because you were shocked by how in demand it is), then check out my complete PHP Development course.

learn php in 2024

This is the only PHP course you need that will take you from complete beginner, all the way to coding your own PHP applications or working with existing PHP ones.

I guarantee you that this is the most comprehensive and up-to-date PHP Bootcamp course to go from absolute beginner to mastering PHP web development, getting hired, and advancing your career.

Once you join, you’ll get access to our private Discord community, where you can ask me questions, as well as chat with other students and current working professionals.


Check it out via the link here, and I'll see you in the community!

More from Zero To Mastery

How To Create A Custom PHP Router preview
Popular
How To Create A Custom PHP Router

Learn how to set up a PHP router for your website with this easy-to-follow step-by-step tutorial (with code examples).

Best Programming Languages To Learn In 2024 preview
Best Programming Languages To Learn In 2024

Want to learn a programming language that pays over $100K, has 1,000s+ of jobs available, and is future-proof? Then pick one of these 12 (+ resources to start learning them today!).

Top 5 In-Demand Tech Jobs For 2024 (+ How To Land A Job In Each!) preview
Top 5 In-Demand Tech Jobs For 2024 (+ How To Land A Job In Each!)

Want to get hired in a tech job in 2024? Pick one of these 5 if you want: 1) High salary 2) Jobs available now 3) Can learn the skills as a complete beginner.