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

1

I have 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 would need to put a phrase like this:

  

You have chosen ketchup , mustard , barbecue .

However, the user who will insert what sauces he wants, he can for example choose only ketchup, or just mustard, or ketchup / mustard / barbecue / mayonnaise / pepper / sweet and sour, 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 build the following structure?

Example: Ketchup, Mustard.

  

You have chosen ketchup , mustard .

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

  

You have chosen ketchup , mustard , barbecue , pimenta , agridoce .

I've thought of using something like this:

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

But as I mentioned, you can only have 1 item in the array or 2 or 3 or 4 or even 10. I also thought about foreach , but I could not get any results.

    
asked by anonymous 29.11.2017 / 14:45

1 answer

2

If it is just for formatting use the function implode() it conveys an array in string 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

    
29.11.2017 / 14:53