PHP is one of the most popular programming languages used to develop web applications and APIs. Linux is the system of choice for serving up your PHP code and is also an ideal PHP development environment.
The PHP explode function is vital for processing user input. It takes a string (a series of characters) and splits it up into smaller strings by a given delimiter to specify the boundary of where the splits should occur.
explode ( $delimiter , $string [, $limit ] )
- $delimiter is the series of characters which will be used to determine the boundaries when splitting the string
- $string is the series of characters which will be split along the defined boundaries
- explode() returns an array of strings, which is the result of splitting the string initially passed to explode()
- Optionally, a $limit can be defined – this should be an integer to determine the maximum number of split items to return – any un-split leftovers will be returned as the last element in the result array
- If $limit is negative, the splitting will start from the end of the string, working backward
In this example, we will split a person’s name into its first, middle, and last names so that they can be stored separately:
$full_name = "Billy James Baker"; $split_names = explode(" ", $full_name); $first_name = $split_names; // "Billy" $middle_name = $split_names; // "James" $last_name = $split_names; // "Baker"
- PHP variables always start with the $ (dollar sign) character!
- The $delimiter has disappeared from the result – once used to determine the boundaries to split the string along, the delimiters are discarded
- The result, which we have stored as $split_names, is a PHP array
- If $delimiter is any empty string (“”), explode() will return FALSE rather than an array
- If $delimiter does not appear in the $string, an array containing a single value – the entire original $string – is returned
$full_name = "Billy James Baker"; $split_names = explode(" ", $full_name, -3); $first_name = $split_names; // "Billy" $middle_name = $split_names; // "James" $last_name = $split_names; // "Baker"
- If $delimiter does not appear in $string and $limit is negative, an empty array will be returned
The PHP explode() function is very handy when dealing with user input – splitting names into first, middle, and last names at the space, or for processing saved files – for example, CSV files from spreadsheet software. Once you start building your own PHP apps, you’ll find other uses for it as well.
To view the official documentation for the PHP explode() function: