explode() into $key=>$value pair

后端 未结 15 621
广开言路
广开言路 2020-12-01 09:24

I have this:

$strVar = \"key value\";

And I want to get it in this:

array(\'key\'=>\'value\')

I tried

15条回答
  •  情深已故
    2020-12-01 09:49

    If you have more values in a string, you can use array_walk() to create an new array instead of looping with foreach() or for(). I'm using an anonymous function which only works with PHP 5.3+.

    // your string
    $strVar = "key1 value1&key2 value2&key3 value3";
    
    // new variable for output
    $result = array();
    
    // walk trough array, add results to $result
    array_walk(explode('&', $strVar), function (&$value,$key) use (&$result) {
        list($k, $v) = explode(' ', $value);
        $result[$k] = $v;
    });
    
    // see output
    print_r($result);
    

    This gives:

    Array
    (
        [key1] => value1
        [key2] => value2
        [key3] => value3
    )
    

提交回复
热议问题