开发者

Is there a more efficient way to match multiple variables in PHP?

Currently, I have 36 variables that are being shuffled (for a really specific WP reason). Anyways so once the variables have shuffled, I am trying to match them with a name. So if $numbers[0] equals lets say 1, then it is supposed to print "John". I am currently using 36 switch case statements to achieve this and I know this is super inefficie开发者_Go百科nt. So I was wondering if there was a smarter way to do this?

Here's my code (for example's sake I am only showing 3 variables & 3 switch cases):

$numbers = range(1, 3);shuffle($numbers);   
switch ($numbers[0]){
    case "1":
        echo $numbers[0] . " is John";
        break;
    case "2":
        echo $numbers[0] . " is Jane";
        break;  
    case "3":
        echo $numbers[0] . " is Mirza";
        break;  
}
switch ($numbers[1]){
    case "1":
        echo $numbers[1] . " is John";
        break;
    case "2":
        echo $numbers[1] . " is Jane";
        break;  
    case "3":
        echo $numbers[1] . " is Mirza";
        break;  
}
switch ($numbers[2]){
    case "1":
        echo $numbers[2] . " is John";
        break;
    case "2":
        echo $numbers[2] . " is Jane";
        break;  
    case "3":
        echo $numbers[2] . " is Mirza";
        break;      
}


First write down all the names into an array:

$names = array(
    0 => 'John',
    1 => 'Jane',
    2 => 'Mirza'
);

After that use a foreach:

foreach($numbers as $number){
    echo $names[$number];
}

Pretty simple, good luck! :)


Not quite sure what your goal is; your example is a bit abstract. But there are two things you can do:

 // loop
 foreach ($numbers as $n) {
     switch($n) { ... }
 }

And then, if the comparison is always against a static list, make it so to avoid the switch statement:

 $compare = array("", "John", "Jane", "Mirza");

 // loop
     print $compare[n];


Something like this should save your day:

$theCase =  array ( " is John", " is Jane", " is Mirza");
$numbers = range(1, 3);shuffle($numbers);     
for ($i=0;$i<3;$i++)
    echo $numbers[$i] . $theCase[$numbers[$i]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜