0

i have a string it looks like this:

brand[split]bmw[split]year[split]2008[split]model[split]730D

I want it to convert to an array that looks like this:

Array ( [brand] => bmw [year] => 2008 [model] => 730D )

is there any easy way to do this?

1 Answer 1

2

explode() will split a string into an array of pieces:

$string = "brand[split]bmw[split]year[split]2008[split]model[split]730D";
$array = explode("[split]", $string);

Then you want to join the first to the second, third to the fourth etc:

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

This returns:

array:3 [▼
  "brand" => "bmw"
  "year" => "2008"
  "model" => "730D"
]
Sign up to request clarification or add additional context in comments.

3 Comments

it creates multiple arrays: Array ( [0] => Array ( [brand] => bmw ) [1] => Array ( [year] => 2008 ) [2] => Array ( [model] => 730D ) [3] => Array ( [] => ) [4] => Array ( [] => ) [5] => Array ( [] => ) )
Just updated the answer with an improved answer (using for instead of foreach).
You're welcome. I don't like the $i++ inside the for loop, but I'm not sure how to $i+2 in the third expression :s

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.