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 limit less than 0: Returns an array -limit elementsequal to 0: Returns an array with only 1 element |
Example
Breaking tags string into an array so that they can
$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
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
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.