1

I am new in php and want to explore how the same thing can be achieved in different ways. I have the following working code and would like to see better ways of coding. Any suggestion is appreciated.

<?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;
?>
The Reaper
  • 67
  • 8
  • 5
    Use a switch statement - http://php.net/manual/en/control-structures.switch.php – Darren Jul 24 '13 at 13:32
  • 1
    This question appears to be off-topic because it is about code review and would be better at http://codereview.stackexchange.com. – deceze Jul 24 '13 at 13:34
  • And get an IDE, netbeans is a free alternative. It automagically indents code, making it prettier ^^ – JimL Jul 24 '13 at 13:35
  • Thanks for giving suggestion. – The Reaper Jul 24 '13 at 13:39
  • 1
    I don't think this fits better in code review. It is very similar to the question of [how to avoid the arrow head antipattern](http://stackoverflow.com/questions/17804005/how-to-prevent-the-arrowhead-anti-pattern) – Carlos Campderrós Jul 24 '13 at 13:39

6 Answers6

3
<?php
$districts = "Aizawl";

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

$city = $districts_city[$districts];
echo $city;
srain
  • 8,944
  • 6
  • 30
  • 42
2
$districts = 'Aizawl';

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

if (isset($map[$districts])) {
  $city = $map[$districts];
} else {
  // show error...
}
Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
2

Use an associative list or a hash table.

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

$city=$array[$districts]
rjv
  • 6,058
  • 5
  • 27
  • 49
0

Bellow code ill be help 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;
 }
 ?>
backtrack
  • 7,996
  • 5
  • 52
  • 99
-1

Use a switch statement

switch ($districts) {
case "Aizawl":
    $city=$fc;
    break;
case "Lunglei":
    $city=$sc;
    break;
case "Saiha":
    $city=$tc;
    break;
}
Nigel B
  • 3,577
  • 3
  • 34
  • 52
-1

Use a switch statement. Also if you aren't using the $fc, $sc, and $tc, variables elsewhere, I would just set the $city variable to the string contents inside the switch statement.

<?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;
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156