2013-07-24 126 views
1

我是新來的PHP,並希望探索如何以不同的方式實現相同的事情。我有以下工作代碼,並希望看到更好的編碼方式。任何建議表示讚賞。任何人都可以給我這個代碼的替代解決方案?

<?php 
$districts = "Aizawl"; 

$fc = "First City"; 
$sc = "Second City"; 
$tc = "Third City"; 

if ($districts == "Aizawl") { 
    $city = $fc; 
} elseif ($districts == "Lunglei") { 
    $city = $sc; 
} elseif ($districts == "Saiha") { 
    $city = $tc; 
} 
?> 
<?php 
echo $city; 
?> 
+5

使用switch語句 - http://php.net/manual/en/control-structures.switch.php –

+1

這個問題似乎是題外話,因爲它是關於代碼審查,並會在更好http://codereview.stackexchange.com。 – deceze

+0

並獲得一個IDE,NetBeans是一個免費的替代品。它自動縮進代碼,使它更漂亮^^ – JimL

回答

3
<?php 
$districts = "Aizawl"; 

$districts_city = array(
    'Aizawl' => 'First City', 
    'Lunglei' => 'Second City', 
    'Saiha' => 'Third City', 
); 

$city = $districts_city[$districts]; 
echo $city; 
+0

您的代碼是最快的。 –

+0

@Zuala,謝謝! – srain

+0

@CarlosCampderrós我一直在嘗試。我的結合很慢! –

-1

使用switch語句

switch ($districts) { 
case "Aizawl": 
    $city=$fc; 
    break; 
case "Lunglei": 
    $city=$sc; 
    break; 
case "Saiha": 
    $city=$tc; 
    break; 
} 
-1

使用switch statement。另外,如果您不使用$fc$sc$tc,其他變量,我只是將$city變量設置爲switch語句內的字符串內容。

<?php 

$districts="Aizawl"; 

$fc="First City"; 
$sc="Second City"; 
$tc="Third City"; 

switch($districts) { 
    case "Aizawl": 
     $city=$fc; 
     break; 
    case "Lunglei": 
     $city=$sc; 
     break; 
    case "Saiha": 
     $city=$tc; 
     break; 
} 

echo $city; 
2
$districts = 'Aizawl'; 

$map = array(
    'Aizawl' => 'First city', 
    'Lunglei' => 'Second city', 
    'Saiha' => 'Third city', 
); 

if (isset($map[$districts])) { 
    $city = $map[$districts]; 
} else { 
    // show error... 
} 
+0

謝謝你給我你的時間。 –

0

婁代碼生病可以幫助FUL

<?php 
$i=2; 

switch ($i) { 
case 0: 
    echo "i equals 0"; 
    break; 
case 1: 
    echo "i equals 1"; 
    break; 
case 2: 
    echo "i equals 2"; 
    break; 
} 
?> 
+0

非常感謝。 –

2

使用關聯列表或哈希表。

$array = array(
    "Aizwal" => "First City", 
    "foo" => "2nd", 
    "bar" => "3rd", 
); 

$city=$array[$districts] 
相關問題