Sandun Isuru Niraj
Sandun Isuru Niraj

Reputation: 461

Get variable data outside from the Switch Statement in PHP

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.

Upvotes: 0

Views: 1466

Answers (3)

Timothy Silooy
Timothy Silooy

Reputation: 11

You're not doing anything with case 2 or default. If you structure it like this, then it should work.

switch ($condition) {
  case 1:
     $userId = $receiver->getMessage();
  break;
  case 2:
     $userId = $receiver->someOtherMessage();
  break;
  default:
     $userId = null;
  break;
}

At a different point you can validate if the userId has actually been set as well.

Upvotes: -1

pavel
pavel

Reputation: 27092

Variable declared inside switch statement is visible outside, of course.

Problem is when isn't declared inside switch, you can avoid it two ways:

  1. $userid = 'default value'; before switch
  2. echo isset($userid) ? $userid : 'default value'; after switch.

Default value can be whatever, if nothing, use empty string.

Upvotes: 2

betaros
betaros

Reputation: 602

On possible way is to declare the variable before you call the switch statement.

$userid = "";
switch (some condition){
   case 1:
   $userid = $receiver->getMessage();
   break;
   case 2:
   break;
 }

 echo $userid;

Upvotes: 0

Related Questions