How to mount a string with each item of an array that can have 1 value or multiple values?

Asked

Viewed 22 times

1

I got the following array at the moment:

array (size=3)
  0 => string 'ketchup' (length=7)
  1 => string 'mustard' (length=7)
  2 => string 'barbecue' (length=8)

I’d need to put together a phrase like that:

You chose ketchup, mustard, barbecue.

However, the user who will insert which sauces he wants, he can for example choose only ketchup, or only Mustard, or ketchup/Mustard/barbecue/mayonnaise/pepper/sweet, ie, the array can have 1 item, or 2 items, or 3 items, or 4 items...or 10 items, depends on the user.

What logic could I use to assemble the following structure?

Example: Ketchup, Mustard.

You chose ketchup, mustard.

Example: Ketchup, Mustard, Barbecue, Mayonnaise, Pepper, Bittersweet.

You chose ketchup, mustard, barbecue, pimenta, agridoce.

I’ve thought about wearing something like this:

echo "Você escolheu $molhos[0], $molhos[1]."

But as I said, you can have only 1 item or 2 or 3 or 4 or even 10. I also thought about the foreach, but I could not reach any result.

1 answer

2


If it’s just to format use the function implode() it converges a string array separating the elements by a delimiter in this case the comma.

$pedido1 = array ('ketchup', 'mustard', 'barbecue', 'pimenta', 'agridoce');
$pedido2 = array ('ketchup', 'mustard');
$pedido3 = array ('ketchup');


echo implode(', ', $pedido1) .'<br>';
echo implode(', ', $pedido2) .'<br>';
echo implode(', ', $pedido3) .'<br>';

Example - replit

  • That’s what I needed. I thought it was something very complex or a very long logic, but in fact it was much simpler than I imagined. Thank you very much rray!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.