有没有更有效的方法来编写这段PHP代码?

时间:2011-05-12 09:42:31

标签: php arrays performance

是否有更有效/更优雅的方式来编写这段代码:

$arr1 = array(
        "weedoit3",
        "alambic3",
        "darwinefficiencyscared",
        "darwinmoneyscared",
        "darwin5scared");

$arr2 = array(
        "darwingouroo",
        "weedoit4",
        "darwin5",
        "darwinefficiency",
        "darwinmoney",
        "pj_half",
        "pj_pole");

$imgArray = array(
        '<img src="images/mail26bg.jpg" width="1440" height="810" class="thiefBg" />',
        '<img src="images/mail25bg.jpg" width="819" height="1024" class="thiefBg" />',
        '<img src="images/mai01.jpg" width="1440" height="960" class="thiefBg" />',
        '<img src="images/mai02.jpg" width="1440" height="960" class="thiefBg" />',
        '<img src="images/mai03.jpg" width="1440" height="1081" class="thiefBg" />');

if (in_array($_GET['ref'], $arr1)) {
    echo $imgArray[0];
}
else if (in_array($_GET['ref'], $arr2)) {
    echo $imgArray[1];
}
else if ($_GET['ref'] == "darwin4" || $_GET['ref'] == "darwinenquete") {
    echo $imgArray[2];
}
else if ($_GET['ref'] == "darwinscared") {
    echo $imgArray[3];
}
else if ($_GET['ref'] == "mai03") {
    echo $imgArray[4];
}

2 个答案:

答案 0 :(得分:4)

制作参考索引的地图。

$refMap = Array('weedoit3' => 0, 'alambic' => 0, ... 'mai03' => 4);

echo $imgArray[$refMap[$_GET['ref']]];

答案 1 :(得分:1)

总是比in_array isset快。

所以你可以像这样定义你的查找数组:

<?php
// Trick here: Use your values as keys and assign them an empty string:
$arr1 = array('weedoit3' => '',
              'alambic3' => '',
              // ...
             );

// Then the check:
if(true === isset($arr1[$_GET['ref'])
{
    // do whatever
}