Home >>PHP String Functions >PHP explode() Function

PHP explode() Function

PHP explode() Function

The PHP explode() function is used to divide or split any given input string in to different strings.

This explode() function is an in-built function of PHP. This explode() function returns an array as a result. The resultant array contains all the strings created by splitting the original given input string.

PHP explode() function splits the input string based on the separator, which means the function will split the string whenever the separator occurs in the string. The $limit is an optional parameter which defines the maximum index of the resultant array.

Syntax :

explode($separator,$string,$limit);

Here is an example of explode() function in PHP:

<html>
<body>

<?php
$str = "Laravel is a compelling model view controller (MVC) architectural pattern PHP framework.";
print_r (explode(" ",$str));
?> 

</body>
</html>
Output:
Array ( [0] => Laravel [1] => is [2] => a [3] => compelling [4] => model [5] => view [6] => controller [7] => (MVC) [8] => architectural [9] => pattern [10] => PHP [11] => framework. )

Here is an example of explode() function in PHP using separator(,) :

<html>
<body>

<?php
$str = "Laravel is a compelling model view controller (MVC) architectural pattern PHP framework.";
print_r (explode(" ",$str));
?> 

</body>
</html>
Output:
Array ( [0] => PHP [1] => Python [2] => C++ [3] => HTML [4] => Laravel [5] => C# )

Here is an example of explode() function in PHP using different limits :

<html>
<body>

<?php
$str = 'PHP,Python,C++,HTML,Laravel,C#';

print "Zero Limit:<br>";
print_r(explode(',',$str,0));
print "<br><br>";

print "One Limit:<br>";
print_r(explode(',',$str,1));
print "<br><br>";

print "Zero Limit:<br>";
print_r(explode(',',$str,4));
print "<br><br>";

print "Negative Limit:<br>";
print_r(explode(',',$str,-1));
print "<br><br>";

print "Negative Limit:<br>";
print_r(explode(',',$str,-3));
?>  

</body>
</html>
Output:
Zero Limit:
Array ( [0] => PHP,Python,C++,HTML,Laravel,C# )

One Limit:
Array ( [0] => PHP,Python,C++,HTML,Laravel,C# )

Zero Limit:
Array ( [0] => PHP [1] => Python [2] => C++ [3] => HTML,Laravel,C# )

Negative Limit:
Array ( [0] => PHP [1] => Python [2] => C++ [3] => HTML [4] => Laravel )

Negative Limit:
Array ( [0] => PHP [1] => Python [2] => C++ )
 

Popular Tutorials