Jump to content

[SOLVED] Split string into associative array


Catfish

Recommended Posts

Hi,

 

What would be the best way to split a string on some delimiter and each part of the string goes into an associative array with the left side of the split as the key and the right side as the value?

 

I tried using explode() but it splits out to a non-associative array, and it looks like split does it too.

 

Basically what I do is read the contents of a settings file where each line has a setting in the format:

variableName=value

into an array - one line to an index.

 

Then I wanted to loop through that array and split each value on "=" to get the variable name and the value but this is where my processing goes wrong. Instead of getting:

$array['variableName'] = "value"

I get:

$array[0] = "variableName"

$array[1] = "value"

 

I remember when I used Perl years ago, I could use regexp's to split a string and use only certain parts of the split string with the $1, $2, $3... etc variables (corressponding to the matched elements of the split up string). Can PHP do someting like this?

Link to comment
Share on other sites

oh i think i may have solved myself on this one...

 

$array[0] = "variableName=value";
foreach ($array as $lineNum => $line)
{
list($key, $value) = explode("=", $line);
$newArray[$key] = $value;
}

 

and I think that should give me:

$newArray['variableName'] = "value"

 

etc.

 

Nice. It works. [sOLVED]

Link to comment
Share on other sites

  • 4 years later...

I know I am reviving this super old thread, but I just wanted to comment that this is exactly the code I needed to help me parse a csv I was using for an e-commerce system. I had a column with data like 11:15.75|100:14.94|250:14.16

and needed the data before the colon to be the index for the data after the colon.

I exploded the string into an array like $array[0] = '11:15.75' and so on, and this code helped me build an array like $array[11]='15.75' and so on.

 

Thanks heaps for your insight!

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.