Chvanikoff
Chvanikoff

Reputation: 1329

Converting a comma separated string of attribute declarations into an associative array

I have a string - something like

$string = 'key1=value1, key2=value2, key3=value3';

How can I get an array from the given string like the following?

$array = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
);

Upvotes: 1

Views: 172

Answers (4)

Your Common Sense
Your Common Sense

Reputation: 157896

If the values (text on the right side of the = symbols) do not have any characters with special meaning in a URL's querystring AND a value will never be null, then you won't have any unexpected results using parse_str() after converting the input to valid querystring format.

$string = 'key1=value1, key2=value2, key3=value3';
parse_str(
    str_replace(", ", "&", $string),
    $array
);
var_export($array);

Demo

Upvotes: 8

gen_Eric
gen_Eric

Reputation: 227240

$a = explode(', ', $string);
$array = array();
foreach($a as $v){
    $x = explode('=', $v);
    $array[$x[0]] = $x[1];
}

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

A naive solution could be :

$string = 'key1=value1, key2=value2, key3=value3';

$array = array();
foreach (explode(', ', $string) as $couple) {
    list ($key, $value) = explode('=', $couple);
    $array[$key] = $value;
}

var_dump($array);

And you'd get the expected array as a result :

array
  'key1' => string 'value1' (length=6)
  'key2' => string 'value2' (length=6)
  'key3' => string 'value3' (length=6)

Upvotes: 3

alexn
alexn

Reputation: 58962

This is exactly what parse_str do. In your case, you need to replace your commas with a &:

$string = 'key1=value1, key2=value2, key3=value3';
$array = parse_str(str_replace(', ', '&', $string));

// Yields
array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
)

Upvotes: 1

Related Questions