Catfish Posted April 4, 2008 Share Posted April 4, 2008 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 https://forums.phpfreaks.com/topic/99522-solved-split-string-into-associative-array/ Share on other sites More sharing options...
nevsi79 Posted April 4, 2008 Share Posted April 4, 2008 maybe use explode have a look at the php site here: http://uk3.php.net/explode hope that helps Link to comment https://forums.phpfreaks.com/topic/99522-solved-split-string-into-associative-array/#findComment-509133 Share on other sites More sharing options...
Catfish Posted April 4, 2008 Author Share Posted April 4, 2008 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 https://forums.phpfreaks.com/topic/99522-solved-split-string-into-associative-array/#findComment-509135 Share on other sites More sharing options...
joshlevinson Posted December 4, 2012 Share Posted December 4, 2012 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 https://forums.phpfreaks.com/topic/99522-solved-split-string-into-associative-array/#findComment-1397548 Share on other sites More sharing options...
Recommended Posts