Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jun 2008
    Thanked 0 Times in 0 Posts

    String In To An Associative Array

    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.

  • #2
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Philadelphia, PA, USA
    Thanked 258 Times in 254 Posts
    Untested, but should work:
    PHP Code:
    $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.
    Last edited by kbluhm; 11-25-2010 at 06:44 PM.

  • Users who have thanked kbluhm for this post:

    Inersha (11-25-2010)


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts