Development PHP: String to Array

Discussion in 'Software' started by jezmck, 28 Apr 2006.

  1. jezmck

    jezmck Minimodder

    Joined:
    25 Sep 2003
    Posts:
    4,456
    Likes Received:
    36
    Hey Guys and Galls,

    I have a string of the form aaa@bbb,ccc@ddd and would like to dynamically convert that to an array of the form ("bbb" => "aaa", "ddd" => "ccc").

    Splitting it by the commas is easy, but then how do I split "aaa@bbb" and use the "bbb" part as the key?
    I could do it manually*, but can't help thinking that there must be a cleaner way of doing it.

    Could there be a neat way of doing it all in one go?

    Any ideas / suggestions welcome and appreciated. (I'm AFK this weekend so may not reply immediately.)

    *- i.e. find the "@" get the preceding, get the 'postceding', add them to the array
     
  2. RTT

    RTT #parp

    Joined:
    12 Mar 2001
    Posts:
    14,120
    Likes Received:
    74
    preg_match_all is probably what you need to use here :) It'll nicely return an array for you as you need.
     
  3. jezmck

    jezmck Minimodder

    Joined:
    25 Sep 2003
    Posts:
    4,456
    Likes Received:
    36
    cheers Rich.
    I just got an answer at EE too:
    Code:
    <?php
    
    $items = explode(',', $string);
    $array = array();
    foreach($items as $item) {
      list($key, $value) = explode('@', $item, 2);
      $array[$key] = $value;
    }
    
    ?>
    
     

Share This Page