explode() function in PHP

PHPProgrammingServer Side Programming

The explode() function is used to split a string by string.

Syntax

explode(delimiter, str, limit)

Parameters

  • delimiter − The boundary string

  • str − String to split

  • limit − Specifies the number of array elements to return.

  • The following are possible values −

    • Greater than 0 - Returns an array with a maximum of limit element(s)

    • Less than 0 - Returns an array except for the last -limit elements()

    • 0 - Returns an array with one element

Return

The explode() function returns an array of strings.

The following is an example −

Example

 Live Demo

<?php
$s = "This is demo text!";
print_r (explode(" ",$s));
?>

The following is the output −

Output

Array
(
   [0] => This
   [1] => is
   [2] => demo
   [3] => text!
)

Let us see another example −

Example

 Live Demo

<?php
$str = 'car,bus,motorbike,cycle';
print_r(explode(',',$str,0));
print "<br>";
?>

The following is the output −

Output

Array
(
   [0] => car,bus,motorbike,cycle
)

Let us see another example −

Example

 Live Demo

<?php
$str = 'car,bus,motorbike,cycle';
print_r(explode(',',$str,2));
?>

The following is the output −

Output

Array
(
   [0] => car
   [1] => bus,motorbike,cycle
)

Let us see another example −

Example

 Live Demo

<?php
$str = 'car,bus,motorbike,cycle';
print_r(explode(',',$str,-1));
?>

The following is the output −

Output

Array
(
   [0] => car
   [1] => bus
   [2] => motorbike
)
raja
Published on 16-Oct-2018 13:14:05
Advertisements