explode – PHP String Functions
Syntax :
Description :
PHP explode function will splits the string by string, into array of elements.
Parameter :
- separator – This is required parameter from which string is splited.
- string – This is required string, which is to be splited.
- limit – This is the Optional parameter. It specifies the number of array
- Greater than 0 – If the value is set to > 0. It returns array with a maximum limit of elements.
- Less than 0 – If the value is set to < 0. It returns an array except for e last -limit of elements.
- 0 (Zero) – If the value is set to 0, then it is treated as 1 (one). It returns array with one element.
Note : This function is binary safe.
Output :
This will return the array of strings.
Related articles : strtok(), str_word_count(), implode(), str_split(), chunk_split().
explode – PHP Functions Example 1 :
<?php $strExample = explode(" ","Hi from tutorialmine's."); print_r($strExample); ?>
In above example ,We have string “Hi from tutorialmine’s.” Now this function will split the string on the basis of seprator i.e Space letter(blank) and returns the arrays of strings. See below is the output of above code.
explode – PHP Functions Example 2 :
If you want to split the string on the basis of separator for e.g. comma ( , ) use below example :
<?php $strExample = "test string 1, test string 2, test string 3, test string 4"; $strOutput = explode(",",$strExample); print_r($strOutput); ?>
Output will be like below:
explode – PHP Functions Example 3 :
Below example will show the example of using zero limit, positive limit, negative limits :
<?php $strExample = "test string 1, test string 2, test string 3, test string 4"; // zero limit print_r(explode(',',$strExample,0)); // This will return one single element of an array. echo"<br>"; // positive limit print_r(explode(',',$strExample,2)); // This will return two elements of an array. echo"<br>"; // negative limit print_r(explode(',',$strExample,-1)); // This will return all elements excluding the last element of an array. ?>
Output will be like below:
Array ( [0] => test string 1 [1] => test string 2, test string 3, test string 4 )
Array ( [0] => test string 1 [1] => test string 2 [2] => test string 3 )