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.

138

Answer

Solution:

Variable declared insideswitch statement is visible outside, of course.

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

  1. $userid = 'default value'; beforeswitch
  2. echo isset($userid) ? $userid : 'default value'; afterswitch.

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

672

Answer

Solution:

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;
797

Answer

Solution:

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.

People are also looking for solutions to the problem: php - Display the events for the current month first then the rest last desc

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.