-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

2
  • 1
    What you're looking for is a foreach loop: php.net/manual/en/control-structures.foreach.php Commented Jul 2, 2016 at 18:15
  • you can try this code for your solution <?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> <?php foreach($states as $key => $value): echo $stateAbbr[$key]."=".$value."<br>"; endforeach; ?> </body> </html> Commented Jul 2, 2016 at 18:19

3 Answers 3

2

You can use double foreach on li

<?php 

     foreach( $states as $index => $state ) {
          echo "<li>" . $state . ' - ' . $stateAbbr[$index] ."</li>
    }
    echo "</ul>"
?>
Sign up to request clarification or add additional context in comments.

2 Comments

There is no and in a foreach loop
@Rizier123 correct ... answer updated with proper indexing
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>

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.