How to split php string into array with explode function
A php string can be converted into an array with the explode function. The splitting of the values is based upon multiple delimiters. The separator might be space, comma, a hyphen, colon, etc.
There are many built in functions that we can use to convert string into array such as explode() or loop methods with split functions. But we'll prefer using explode function.
explode(separator, string)
The PHP explode function accepts the separator (delimiter) and string as arguments. The first argument is a separator that might be space, comma, hyphen, colon or even some alphabetic character. And the second argument is the string we want to split into array.
$string = "explode function splits the string into array based upon the separator as break point";
$arr = explode(" ", $string);
// $arr = [explode,function,splits,the,string,into,array,based,upon,the,separator,as,break,point];
In the above-given example, the string has been split into an array. The string is split wherever space delimiter is encountered as separator.
We will practice the other separators as break points to split string into array.
split a string by comma into array
A CSV (Comma Separated Values) file uses this format of data to display the values on sheets. explode function splits the string values separated by comma into an array.
$string = "Name, Surname, Website";
$arr = explode(",", $string);
// $arr = [Name,Surname,Website];
It breaks the string values separated by comma into an array.
split a string by hyphens into array
For example, if we get the current URL with $_SERVER['REQUEST_URI']. This URL contains the hyphens as separators.
$url = "php-split-string-into-array";
$arr = explode("-", $url);
// $arr = [php,split,string,into,array];
In the above-example,we are splitting the string URL into an array using the hyphens as the breakpoint.
split a string by colon into array
You can see this format of data in linux. The values or fields in a string are separated by colon.
$string = "Node:PID:PPID:PPFDT";
$arr = explode(":", $string);
// $arr = [Node,PID,PPID,PPFDT];
We can extract different field values into an array. The hyphens are beings used as the separator.
Was this article helpful?