The explode function in PHP is very useful in developing any web application or website. In this article, I will explain the explode function and give you real-life example.
PHP explode()
explode() function splits/break a word into an array based on the separator provided.
explode( separator, string, limit )
separator
required
A character or string which specifies from where to break the word.
string
required
The actual string that will be broken into array
limit
optional
It will be an integer.greater than 0: Returns an array with maximum number of elements as limitless than 0: Returns an array except the last -limit elementsequal to 0: Returns an array with only 1 element
Example
Breaking tags string into an array so that they can displayed properly on webpage. The tags in the string are separated by comma.
$tags = 'wordpress,php,php explode,php implode,php functions';// without limit parameter$tags_arr = explode(',', $tags);/* Output:Array ( [0] => wordpress [1] => php [2] => php explode [3] => php implode [4] => php functions )*/// with limit = 0$tags_arr = explode(',', $tags, 0);/* Output:Array ( [0] => wordpress,php,php explode,php implode,php functions )*/// with limit = 4$tags_arr = explode(',', $tags, 4);/* Output:Array ( [0] => wordpress [1] => php [2] => php explode [3] => php implode,php functions ) */// with limit = -2$tags_arr = explode(',', $tags, -2);/* Output:Array ( [0] => wordpress [1] => php [2] => php explode ) */
Example Explained:Without limit parameter: When no limit parameter is provided, the whole string is broken into array elements based on the separator.With limit equals 0: It returns an array with only 1 element. In other words, it converts the string into an array element without breaking it.With limit equals 4: Breaks the string from the start until total array elements equal to 4.With limit equals -2: Breaks the string into array elements based on the separator except the last 2 elements.
If you like my explanation, please click on the bell icon on right bottom corner of the page to subscribe so that you will get notifications of our future posts.

