0

Imagine this:

$array(type=>$user_input);

$level1 = "arbitrary 1";
$level2 = "arbitarty 2";

if( $type && $type != '' ){
        switch ($type){
            case 'level1':
                $levels = $level1;
                break;
            case 'level2':
                $levels = $level2;
                break;
            }
    }else{
        $levels = $level1 . $level2;
    }

This works, but seems repetitive -- especially with 10, 20 levels...

How would I do this:

$array(type=>$user_input);

$level1 = "arbitrary 1";
$level2 = "arbitarty 2";

if( $type && $type != '' ){
        $levels = (use the type contained in the variable named by the user_input)
    }else{
        $levels = $level1 . $level2;
    }

Since I have lost my ability to speak in proper English, I hope my code explanation is self-explanatory.

2
  • 1
    $array(type=>$user_input); makes absolutely no sense to me... What is this suposed to do? Commented Oct 8, 2013 at 23:00
  • The array is built by other code that contains a "user input" of level1, level2, level3 etc... Commented Oct 8, 2013 at 23:05

3 Answers 3

1

You could use variable variables:

$level = $$type;
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome. I was just looking at variable variables... what a rabbit hole ;)
Indeed, it is. You really need to be careful when using it in order to make sure there's no unexpected value in $type which is why using an array as other have suggested may be the better approach.
0

Not sure what you are trying to achieve here, but if I understand you correctly I would probably do something like this:

$levelList = array(
 'level1' => "arbitrary 1",
 'level2' => "arbitarty 2"
);

if ($type){
   $levels = isset($levelList[$type]) ? $levelList[$type] : implode('', $levelList);
}

using the $$variable syntax is valid indeed, but it seems a bit dirty to me, and an array seems just more appropriate here anayway

Comments

0

Wouldn't it make more sense to use an array?

$levels = array('Level 1', 'Level 2', 'Level 3'); 
$key    = array_search($type, $levels);
$result = $levels[$key];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.