Anonymous
Anonymous

Reputation: 1094

How to set values to a variable inside switch case, and call that variable outside switch in Php

I have some dynamic values to place in variable, but for testing purpose I am taking dummy values, The problem is that I want to set value to the variable inside switch case by checking different conditions and call that variable outside switch case to print out put but I am not getting any value while echo .

So how to print the value by calling that variable?

<?php 

$favcolor = "red";
$color_val;

switch ($favcolor) {
    case "red":
        return $color_val="Your favorite color is red!";

  // echo "Your favorite color is red!";
        break;
    case "blue":
        return $color_val="Your favorite color is blue!";
        break;
    case "green":
        return $color_val="Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, nor green!";
}
echo $color_val;

Upvotes: 0

Views: 585

Answers (1)

Russ J
Russ J

Reputation: 838

You need to remove the "return" keyword from your switch. It doesn't do what I think you are intending for it to do there.

Upvotes: 4

Related Questions