In PHP, arrays and strings are so common that PHP has two functions that can be converted between strings and arrays.
The code is as follows:
$ Array = explode (separator, $ string );
$ String = implode (glue, $ array );
The key to using and understanding these two functions is the relationship between the separator and glue. When an array is converted into a string, the delimiter is set-the character or code that is inserted into the array value in the generated string.
On the contrary, when you convert a string into an array, you must specify a delimiter to mark what should be converted into an independent array element. For example, start with a string:
$ S1 = 'mon-Tue-Wed-Thu-fri ';
$ Days_array = explode ('-', $ s1 );
The $ days_array variable is now an array with five elements. the Mon index of the element is 0, and the Tue index is 1.
$ S2 = implode (',', $ days_array );
$ S2
Variables are now a list of days in a week separated by commas: Mon, Tue, Wed, Thu, Fri
Example 1. explode () example
The code is as follows:
// Example 1
$ Pizza = "piece1 piece2 piece3 piece4 piece5 piece6 ";
$ Pieces = explode ("", $ pizza );
Echo $ pieces [0]; // piece1
Echo $ pieces [1]; // piece2
// 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 ;//*
?>
Example 2. limit parameter example
The code is as follows:
$ Str = 'one | two | three | four ';
// Positive limit
Print_r (explode ('|', $ str, 2 ));
// Negative limit
Print_r (explode ('|', $ str,-1 ));
?>
The above example will be output:
Array
(
[0] => one
[1] => two | three | four
)
Array
(
[0] => one
[1] => two
[2] => three
)
Note: This function can be safely used for binary objects.