Friday, January 4, 2013

PHP explode function

PHP explode function

The explode function is used to split a string by a specified string into pieces i.e. it breaks a string into an array.

The explode function in PHP allows us to break a string into smaller text with each break occurring at the same symbol. This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

for more details please visit http://php.net/manual/en/function.explode.php

array explode ( string $delimiter , string $string [, int $limit ] )

explode function request 3 parameters, but the last one is optional. Let see what are these parameters.

$delimiter - to break a string into smaller text with each break occurring at the same symbol, this would be the symbol
$string - String that you want to split
$limit - Limit is optional param but would may be tricky. You must concern following points when you are try to use limit.
  • If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
  • If the limit parameter is negative, all components except the last -limit are returned.
  • If the limit parameter is zero, then this is treated as 1.
Let see some example codes:

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));


Above code will output the following:
Array
(
    [0] => one
    [1] => two|three|four
)

<?php
$str = 'one|two|three|four';

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));


Above code will output the following:
Array
(
    [0] => one
    [1] => two
    [2] => three
)


<?php
$str = 'one|two|three|four';

// limit with 0 and 1 would be same
print_r(explode('|', $str, 0));



Above code will output the following:

Array
(
    [0] => one|two|three|four
)