0

I have an $_POST array that looks like this.

Array (
    [burrito] => Cilantro
    [pizza] => Array ( [0] => Avocado [1] => Italian Sausage [2] => pepperoni )
) 

I need $_POST variable to be dynamic. So, burrito & pizza is not fixed variable.

I want this to look like:

burrito=>Cilantro , pizza=>(Avocado, Italian Sausage, pepperoni)

I suspect I need to use:

foreach($_POST as $key => $value){

    foreach($_POST[$key] as $d => $k){

    }

}

And the implode() function.

But I am stuck here. Whatever I do, the result would not come out.

0

2 Answers 2

1

You are on the right track with implode(). But since you have values which only contain a string and some which contain an array, you have to check for that.

So you can do something like this:

Simply loop through your array and if the value is_array() then return the imploded array back, otherwise just the single value, e.g.

foreach($_POST as $k => $v) {
    echo "$k => " . (is_array($v) ? "(" . implode(",", $v). ")" : $v) . "<br>";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Always love what you come up with Rizier!
Worked exactly what I wanted!
1

You can use json_encode() to convert an array into a string. Then your array will look like this:

{"burrito":"Cilantro","pizza":["Avocado","Italian Sausage","pepperoni"]}

You can also convert the string back into an array using json_decode().

1 Comment

Thank you! This method does work beautifully but not 100% the way I want to look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.