-1

I have the following PHP code:

<?php
 $states = array("Alabama","Alaska","Arizona","Arkansas",
 "California","Colorado","Connecticut","Delaware",
"Florida","Georgia","Hawaii","Idaho",
"Illinois","Indiana","Iowa","Kansas","Kentucky");
 $stateAbbr = array("AL","AK","AZ","AR","CA","CO","CT","DE",
 "FL","GA","HI","ID","IL","IN","IA","KS","KY");
?>
<!DOCTYPE html>
<html>
<body>
 <h1>List of States</h1>
</body>
</html>

Now I need to add a PHP code to print the state and state abbreviation as a table by loop through all elements, using a for loop, and echo elements from both arrays at every index

Kaky
  • 11
  • 3
  • 1
    What you're looking for is a `foreach` loop: http://php.net/manual/en/control-structures.foreach.php – Qirel Jul 02 '16 at 18:15
  • you can try this code for your solution `

    List of States

    $value): echo $stateAbbr[$key]."=".$value."
    "; endforeach; ?> `
    – NikuNj Rathod Jul 02 '16 at 18:19

3 Answers3

2

You can use double foreach on li

<?php 

     foreach( $states as $index => $state ) {
          echo "<li>" . $state . ' - ' . $stateAbbr[$index] ."</li>
    }
    echo "</ul>"
?>
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

You can also combine the arrays and then loop throw, creating the table rows.

    <table>
      <thead>
        <tr>
          <th>Code</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
      <?php
        foreach (array_combine($stateAbbr, $states) as $code => $name) {
            echo '<tr><td>' . $code . '</td><td>' . $name . '</td></tr>';
        }
      ?>
      </tbody>
    </table>
Claudio
  • 5,078
  • 1
  • 22
  • 33
0

You could make your array like this:

<?php
$states = array(
"Alabama" => "AL",
"Alaska" => "AK",
"Arizona" => "AZ",
"Arkansas" => "AR", 
"California" => "CA",
"Colorado" => "CO",
"Connecticut" => "CT",
"Delaware" => "DE", 
"Florida" => "FL",
"Georgia" => "GA",
"Hawaii" => "HI",
"Idaho" => "ID", 
"Illinois" => "IL",
"Indiana" => "IN",
"Iowa" => "IA",
"Kansas" => "KS",
"Kentucky" => "KY"
);

Then print it like this or in any tag you want:

<!DOCTYPE html>
<html>
<body>
    <h1>List of States</h1>
    <?php
        foreach($states as $state => $abbr)
        {
            echo $state.' - '.$abbr.'<br />';
        } 
    ?>
</body>
</html>

Regards.

theMohammedA
  • 677
  • 7
  • 11