Saturday, July 18, 2009

php explode and implode

Explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter .

Note:If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned. For any other limit , an array containing string will be returned.

Example:
// Example 1
$example = "test1 test2 test3 test4 test5 test6";
$pieces = explode(" ", $example);
echo $pieces[0]; // test1
echo $pieces[1]; // test2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

limit parameter examples

$str = 'one|two|three|four';

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

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

Output is
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)


Implode
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Note: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

Syntax:
string implode ( string $glue , array $pieces )
string implode ( array $pieces )

Example:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

?>

0 comments:

Post a Comment