PHP arrays and strings convert to each other to implement the method
- 2020-05-30 19:43:14
- OfStack
$array=explode(separator,$string);
$string=implode(glue,$array);
The key to using and understanding these two functions is the delimiter (separator) and glulam (glue) relationship. When converting an array to a string, the glulam -- the character or code that will be inserted between the array values in the generated string -- is set.
Instead, when converting a string into an array, specify the delimiter that marks what should become a separate array element. For example, start with a string:
= 'Mon - Tue - $s1 Wed Thu - Fri';
$days_array = explode (' - ', $s1);
The $days_array variable is now an array of five elements whose element Mon has an index of 0, Tue has an index of 1, and so on.
$s2 = implode (', '$days_array);
$s2
Variable is a comma-separated list of now each day in a week's list: Mon, Tue, Wed, Thu, Fri
Example 1. explode() example
<?php
// The sample 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// The sample 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>
Example 2. Sample limit parameter
<?php
$str = 'one|two|three|four';
// The positive limit
print_r(explode('|', $str, 2));
// negative limit
print_r(explode('|', $str, -1));
?>
The above example will output:
Array
(
[0] = > one
[1] = > two|three|four
)
Array
(
[0] = > one
[1] = > two
[2] = > three
)
Note: this function is safe for binary objects.