如何将多个值返回给Switch?

How can I return more than one value using switch in PHP?

In the example below, I'm trying to return category1, category2, category3 for product1, but with the code below the switch statement only returns one value.

switch ($product) {
    case "product1":
        $category = "category1";
        break;
    case "product1":
    case "product2":
        $category = "category2";
        break;
    case "product1":
    case "product2":
    case "product3":
        $category = "category3";
        break;
}

Is there a way to add multiple values to $category? And I would like to have the values separated by a comma, so I can use them as tags later on.

you can do it with following.

$category = array();
switch($product)
{

case "product1":
  $category[] = "category1";

case "product2":
  $category[] = "category2";

case "product3":
  $category[] = "category3";
}
return implode(',',$category);

by appending the string and removing break statement will allow you to check all possible cases in switch.

You should use an array if you want to return multiple values.

// We're going to store or multiple categories into an array.
$categories = array();
switch ($product) {
    case "product1":
        $categories[] = "category1";
        // This case label doesn't have a break statement, and thus it 'falls through'
        // to the next case label, which is "product2". That code block will also be
        // executed.
    case "product2":
        $categories[] = "category2"
    case "product3":
        $categories[] = "category3";
}

This snippet omits breaks at the end of the case code blocks, thus it uses switch case fallthrough: if $product == "product1", then the matching case label will be executed, but 'falls through' to the label product2, which will also be executed, and so on.

If $product == "product1", then $category is an array with the values category1, category2 and category3.

Then you can concatenate the strings in the array, separated with a comma, like this:

echo implode(",", $categories);

Notice: Sometimes, it's useful to use case fall through, but be advised, it is prone to errors. If your fallthrough is intended, then it is strongly recommended that you add a comment to notify other programmers that this fallthrough is intentional. Otherwise, they might think that you accidentally forgot the break statement.