Home  >  Article  >  Backend Development  >  How to convert between PHP arrays and strings

How to convert between PHP arrays and strings

巴扎黑
巴扎黑Original
2017-08-04 16:52:311364browse

Since the two variable types, array and string, are so commonly used in PHP, PHP has two functions that can convert 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 separator and glue. When converting an array to a string, glue characters - characters or codes that will be inserted between the array values ​​in the resulting string - are set.

In contrast, when converting a string to an array, you specify a delimiter, which is used to mark what should become independent array elements. 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 5 elements, whose elements Mon are at index 0, Tue at index 1, and so on.
 $s2=implode(',',$days_array);
 $s2
The variable is now a comma-separated list of days of the week: Mon, Tue, Wed, Thu, Fri

Example 1. explode() example

The code is as follows:

<?php 
// 示例 1 
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; 
$pieces = explode(" ", $pizza); 
echo $pieces[0]; // piece1 
echo $pieces[1]; // piece2 
// 示例 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:

<?php 
$str = &#39;one|two|three|four&#39;; 
// 正数的 limit 
print_r(explode(&#39;|&#39;, $str, 2)); 
// 负数的 limit 
print_r(explode(&#39;|&#39;, $str, -1)); 
?>

The above example will output:

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

Note: This function can be used safely for binary objects.

The above is the detailed content of How to convert between PHP arrays and strings. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP array traversalNext article:PHP array traversal