I have this:
$strVar = \"key value\";
And I want to get it in this:
array(\'key\'=>\'value\')
I tried
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
)