0

I have string and need convert to array.

<?php
$str = '"en"=>"English" , "fr"=>"French" , "de"=>"German"';
$array = array($str);
print_r($array)
?>

I need this result:

Array
(
    [en] => English
    [fr] => French
    [de] => German
)

Is there a function in PHP to do this?

when try below code, I get good result.but when use uppern code, NO! How to convert String variable for input array?

<?php
//$str = '"en"=>"English" , "fr"=>"French" , "de"=>"German"';
$array = array("en"=>"English" , "fr"=>"French" , "de"=>"German");
print_r($array)
?>
3
  • That looks like an associative array. The evil eval comes to mind. Don't do it. Instead try a series of explode and trim or even preg_match. Commented Jun 23, 2014 at 8:57
  • No, this is not a generally supported serialisation format. You'll have to write your own function for this custom format. Or use something that is generally supported, like JSON. Commented Jun 23, 2014 at 8:57
  • 3
    Where does this come from? How did it end up being a String in the first place? Commented Jun 23, 2014 at 9:03

2 Answers 2

4

As said in the comments, you should probably look in to json if you have a way of changing the string, else something like this will suffice:

$str = '"en"=>"English" , "fr"=>"French" , "de"=>"German"';
$first = explode(' , ',$str);

$second = array();
foreach($first as $item) {
    list($key, $value) = explode('=>', $item);
    $second[str_replace('"', '', $key)] = $value;
}

Which returns:

Array
(
    [en] => "English"
    [fr] => "French"
    [de] => "German"
)

Example

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

1 Comment

I would remove the quotes from the keys. Otherwise you will have to access them with $second["\"fr\""];
1

You can use eval, In your case could be something like this:

$str = '"en"=>"English" , "fr"=>"French" , "de"=>"German"';
eval("\$array = array($str);");
print_r($array)

Result:

Array
(
    [en] => English
    [fr] => French
    [de] => German
)

2 Comments

Thank YOU!this is a BEST answer for me.I need this!Like!
@putvande my $str variable is not user input and generated by php. Yes, if use eval for user input, maybe occured security bug.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.