Skip to content
Advertisement

Convert PHP String to Associative Array

I have a string that looks like the below:

Name,Age,Location
Jo,28,London

How would I convert this into an associative array so it reads like this:

Array
(
    [Name] => Jo
    [Age] => 28
    [Location] => London
)

I’ve tried to explode the string and manipulate it that way but got nowhere fast ($body = explode(',', $body);) I tried to use array_map() but it expected an array in the first place.

I’ve looked through a few articles (PHP CSV to Associative Array with Row Headings) but again they are using array_map().

Advertisement

Answer

You are trying to over-engineer simple thing, which result in wasting too much time for having task done.

$str = "Name,Age,LocationnJo,28,London";

$lines = explode("n", $str);
$keys = explode(',', $lines[0]);
$vals = explode(',', $lines[1]);

$result = array_combine($keys, $vals);

But even ordinary loop would do the trick in your case and this is what you should end up with unless you had better ideas:

$result = []; 
for($i=0; $i<count($keys); $i++) {
   $result[$keys[$i]] = $vals[$i];
}

I also recommend getting thru list of available built-in array functions for future benefits.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement