View Full Version : String In To An Associative Array

11-25-2010, 06:16 PM
So far I've been happily using the explode() function to turn simple strings like "key1, key2, key3" etc. in to arrays using the comma and space as the separator.

However, what's the best method for turning a string in to an associative array? For example, if I have an string like "key1 => value1, key2 => value2, key3 => value3" etc., whats the best way to turn this in to an associative array?

Furthermore, that particular string is just an example. Is there a better way to write strings if I know I'm going to turn them in to an associative array at some point?

The reason I'm asking is because I'm not able to store associative arrays in a mysql field, so I'm thinking that storing a string and then transforming it would be the easiest way of doing it.

11-25-2010, 06:31 PM
Untested, but should work:

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

// manipulate into a query string format
$string = str_replace( array( ' => ', ', ' ), array( '=', '&' ), $string );

// parse the query string into an associative array
parse_str( $string, $array );

// what do we have?
print_r( $array );

This assumes there will always be a single whitespace on either wide of `=>`, and only a single whitespace to the right of `,`... regular expressions, or a combination of explode()/trim()/implode(), can be used to handle spaces with greater lenience.

Now, for the better solution.

A better alternative to store arrays as a string would be to pass them through serialize(), then store them as a string. When you retrieve them, you pass the serialized array through unserialize(), and you have your original array in tact, types and all.