I have this:
$strVar = \"key value\";
And I want to get it in this:
array(\'key\'=>\'value\')
I tried
If you have long list of key-value pairs delimited by the same character that also delimits the key and value, this function does the trick.
function extractKeyValuePairs(string $string, string $delimiter = ' ') : array
{
$params = explode($delimiter, $string);
$pairs = [];
for ($i = 0; $i < count($params); $i++) {
$pairs[$params[$i]] = $params[++$i];
}
return $pairs;
}
Example:
$pairs = extractKeyValuePairs('one foo two bar three baz');
[
'one' => 'foo',
'two' => 'bar',
'three' => 'baz',
]
Don't believe this is possible in a single operation, but this should do the trick:
list($k, $v) = explode(' ', $strVal);
$result[ $k ] = $v;
I found another easy way to do that:
$a = array_flip(explode(' ', $strVal));