phparrayskey-valueassociative-arraystring-parsing

Parse a string resembling PHP array syntax into an associative array


I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:

$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);

This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:

$MyArray = array('Type'=>'Honda', 'Color'=>'Red');

But my probem is that the the data is already in the form of a string.


Solution

  • There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.

    An example specification for the custom function:

    Note: if your strings contain delimiters this will be more challenging.