Get variable data outside from the Switch Statement in PHP
288
In my code I have a variable assign of some data inside a switch statement. But that variable not output the data when it calls outside the switch statement. Sample code is here.
switch (some condition){
case 1:
$userid = $receiver->getMessage();
break;
case 2:
break;
}
echo $userid;
how I solve this problem.
Answer
Solution:
Variable declared inside
switch
statement is visible outside, of course.Problem is when isn't declared inside switch, you can avoid it two ways:
$userid = 'default value';
beforeswitch
echo isset($userid) ? $userid : 'default value';
afterswitch
.Default value can be whatever, if nothing, use empty string.
Answer
Solution:
On possible way is to declare the variable before you call the switch statement.
Answer
Solution:
You're not doing anything with case 2 or default. If you structure it like this, then it should work.
At a different point you can validate if the userId has actually been set as well.