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)
?>
Alex
  • 21
  • 2
  • 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`. – Sergiu Paraschiv Jun 23 '14 at 08: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. – deceze Jun 23 '14 at 08:57
  • 3
    Where does this come from? How did it end up being a String in the first place? – putvande Jun 23 '14 at 09:03

2 Answers2

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

deceze
  • 510,633
  • 85
  • 743
  • 889
Darren
  • 13,050
  • 4
  • 41
  • 79
  • 2
    I would remove the quotes from the keys. Otherwise you will have to access them with `$second["\"fr\""];` – putvande Jun 23 '14 at 09:06
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
)
Mauro
  • 1,447
  • 1
  • 26
  • 46
  • Thank YOU!this is a BEST answer for me.I need this!Like! – Alex Jun 23 '14 at 09:08
  • 2
    @putvande my $str variable is not user input and generated by php. Yes, if use `eval` for user input, maybe occured security bug. – Alex Jun 23 '14 at 09:23