Home >Backend Development >PHP Tutorial >How to convert php string into array

How to convert php string into array

零到壹度
零到壹度Original
2018-04-13 13:35:0810325browse

The content of this article is to share with you how to convert PHP strings into arrays. As a PHP programmer, Xinyi’s first reaction is to think of the two functions explode() and implode(). Shinichi also uses the function inside to convert it into an array. has certain reference value. Friends in need can refer to

con[1]=28&selt[1]=1&con[2]=29&selt[2]=4&con[3]=26&selt[3]=4
&con[4]=30&selt[4]=2&con[5]=4&selt[5]=1&con[6]=11&con[7]=12

. The above is the string that netizens need to convert into a PHP array; The following is also the PHP conversion code provided by Xinyi

<?php
$str = &#39;con[1]=28&selt[1]=1&con[2]=29&selt[2]=4&con[3]=26&selt[3]=4&con[4]=30&selt[4]=2&con[5]=4&selt[5]=1&con[6]=11&con[7]=12&#39;;
$arr = explode(&#39;&&#39;,$str);
$arr2 = array();
foreach($arr as $k=>$v){
        $arr = explode(&#39;=&#39;,$v);
        $arr2[$k] = $arr[1];
}
print_r($arr2);
?>
//输出
Array
(
    [0] => 28
    [1] => 1
    [2] => 29
    [3] => 4
    [4] => 26
    [5] => 4
    [6] => 30
    [7] => 2
    [8] => 4
    [9] => 1
    [10] => 11
    [11] => 12
)
//第二个
<?php
$str = &#39;con[1]=28&selt[1]=1&con[2]=29&selt[2]=4&con[3]=26&selt[3]=4&con[4]=30&selt[4]=2&con[5]=4&selt[5]=1&con[6]=11&con[7]=12&#39;;
$arr = explode(&#39;&&#39;,$str);
$arr2 = array();
foreach($arr as $k=>$v){
        $arr = explode(&#39;=&#39;,$v);
        $arr2[$arr[0]] = $arr[1];
}
print_r($arr2);
?>
//输出
Array
(
    [con[1]] => 28
    [selt[1]] => 1
    [con[2]] => 29
    [selt[2]] => 4
    [con[3]] => 26
    [selt[3]] => 4
    [con[4]] => 30
    [selt[4]] => 2
    [con[5]] => 4
    [selt[5]] => 1
    [con[6]] => 11
    [con[7]] => 12
)

Xinyi's PHP code can also solve the problem of converting strings into arrays. Finally, phper netizens should find out in the manual that the parse_str() function can convert a string into a PHP array; let’s introduce the description of the parse_str() function so that you can have a good impression in your mind.
The parse_str() function converts the query Strings are parsed into variables.

parse_str(string,array)
string:需要转换的字符串;
array:返回到一个数组中;
如果没有设置array的话就覆盖同名变量

Related recommendations:

Related methods of converting PHP arrays to strings and converting PHP strings to arrays

PHP arrays and characters Implementation method of converting strings to each other

php operates strings and converts them into arrays

The above is the detailed content of How to convert php string into array. 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