Home  >  Article  >  Backend Development  >  How to convert string into array in php

How to convert string into array in php

WJ
WJOriginal
2020-05-29 16:28:483163browse

How to convert string into array in php

The content of this article is to share with you how to convert PHP strings into arrays. As a PHP programmer, the first reaction is to think of explode() and implode(). function.

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 needs to be converted into a PHP array; the PHP conversion code is provided below

<?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
)

The above PHP code can also solve the problem of converting strings into arrays. Let’s introduce the description of the parse_str() function so that you can have a good impression in your mind.

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

Related recommendations: php中文网

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