OliverSamson43
OliverSamson43

Reputation: 53

PHP: variable based on array contents

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.

Upvotes: 0

Views: 52

Answers (3)

AlexP
AlexP

Reputation: 9857

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

Upvotes: 0

Pevara
Pevara

Reputation: 14310

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

Upvotes: 0

TheWolf
TheWolf

Reputation: 1385

You could use variable variables:

$level = $$type;

Upvotes: 1

Related Questions