php explode – A php function which splits a string int to an array

The explode() function breaks a string into an array.

Syntax:-
explode(separator,string,limit);

Example1 :-

<?php
$my_string  = “part1 part2 part3 part4 part5 part6”;
$my_array = explode(” “, $my_string);
echo “<pre>”;
print_r($my_array);
echo “</pre>”;
?>

Output :-

Array
(
    [0] => part1
    [1] => part2
    [2] => part3
    [3] => part4
    [4] => part5
    [5] => part6
)

Separator :- Separator specifies where to break string.
Here Separator is “space”.
string :- String specifies which string to split.
limit :- limit is optional parameter,Specifies the maximum number of array elements to return.

Example2 :-

<?php
$my_string  = “part1 part2 part3 part4 part5 part6”;
$my_array = explode(” “, $my_string,1);
echo “<pre>”;
print_r($my_array);
echo “</pre>”;
?>

Output :-

Array
(
    [0] => part1 part2 part3 part4 part5 part6
)

Limit is given, it means it will return whole string as only one array.

Example3 :-

<?php
$my_string  = "part1 part2 part3 part4 part5 part6";
$my_array = explode(" ", $my_string,3);
echo "<pre>";
print_r($my_array);
echo "</pre>";
?>
Output :-
Array
(
    [0] => part1
    [1] => part2
    [2] => part3 part4 part5 part6
)
Limit is given 1, it means it will return whole string as only one array.
Advertisements

I like to hear from you about this !!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s