0

Possible Duplicate:
PHP - split String in Key/Value pairs

Hey experts how would I turn this string into a usable array?

fname=first_name,lname=last_name,phone=phone_number,street1=address,city=city,state=state,zip=zip,carrier=carrier

Community
  • 1
  • 1
Jeff Long
  • 69
  • 9

7 Answers7

2
array_map(function ($i) { return explode('=', $i); }, explode(',', $string))
deceze
  • 510,633
  • 85
  • 743
  • 889
1

something along the lines of-- foreach(split($long_str, ',') as $pair) { $pair_arr = split($pair, '='); $map[$pair[0]] = $pair[1]; }

I'm sure the syntax is off, but it should give you the idea.

Jeremy
  • 1,015
  • 4
  • 11
  • 20
0
$arr = array();

$pieces = explode(",", $str);
foreach($pieces as $piece)
{
    list($key, $value) = explode('=', $piece);
    $arr[$key] = $value;
}
0
$res = array();
for ($i in explode(',', $input)) {
    $parts = explode('=', $i);
    $res[$parts[0]] = $parts[1];
}
Borealid
  • 95,191
  • 9
  • 106
  • 122
0

Try this:

$chunks = explode(',', $string);
$arr = array();
foreach($chunks as $set)
{
    $kv = explode('=',$set);
    $arr[$kv[0]] = $kv[1];
}

That will give you:

$arr['fname'] = 'first_name';
$arr['lname'] = 'last_name';
$arr['phone'] = 'phone_number';
$arr['street1'] = 'address';
$arr['city'] = 'city';
$arr['state'] = 'state';
$arr['zip'] = 'zip';
$arr['carrier'] = 'carrier';

Here's php manual page on explode.

rockerest
  • 10,412
  • 3
  • 37
  • 67
0

$str = "fname=first_name,lname=last_name,phone=phone_number,street1=address,city=city,state=state,zip=zip,carrier=carrier";

parse_str(str_replace(",", "&", $str), $result);

var_dump($result);

steve
  • 608
  • 1
  • 5
  • 16
0
/**
 * Converts a string to an associative array.
 *
 * Usage:
 * 
 * echo strToAssocArray("k=v,k2=v2", "=", ",");
 * // outputs array('k' => 'v', 'k2' => 'v2')
 *
 * @param string $str the string
 * @param string $keyValueSep the separator between key and value
 * @param string $recordSep the record separator
 * @return array the resulting associative array
 */
function strToAssocArray($str, $keyValueSep, $recordSep)
{
    $sep1 = preg_quote($keyValueSep);
    $sep2 = preg_quote($recordSep);
    $regex = '/(.*?)' . $sep1 . '(.*?)(?:' . $sep2 . '|$)/';
    preg_match_all($regex, $str, $matches);
    return array_combine($matches[1], $matches[2]);
}
JRL
  • 76,767
  • 18
  • 98
  • 146