1

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',
);
2
  • 1
    Why you are not using google ? stackoverflow.com/questions/5100530/… Commented Mar 30, 2011 at 20:48
  • what's the original source of the string? Commented Mar 30, 2011 at 20:50

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

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',
)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.