Generic foreach array key question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AntonLargiader
    Member
    • Dec 2009
    • 87
    • 4.0.0

    Generic foreach array key question

    I've been looking for examples of this but haven't found one that's clear to me.

    I have a simple array of arrays:

    $race = array(
    "race1" => array("Date 1", "Town 1"),
    "race2" => array("Date 2", "Town 2")
    );

    I want a foreach loop that will yield the key and a specific value for a dropdown menu:
    Code:
    <option value="race1">Town 1</option>
    <option value="race2">Town 2</option>
    So if I wanted to pull out "race1, Town 1" and "race2, Town 2" how do I do that? I know it's got to be simple but I can't find it. I'm playing with array_keys($race) as $row which gets me the key but I have no idea how to get the specific value. I tried using that key to just call it from the array but my syntax must have been wrong; I used $race['$row'][1].
    My VB forum: BMWRA
  • AntonLargiader
    Member
    • Dec 2009
    • 87
    • 4.0.0

    #2
    I found it. I was on the right track but it was too hard to get the syntax correct in the select line.

    This worked:

    Code:
    foreach(array_keys($race) as $row) {
       $n = $race[$row][1];
       echo "<option value=\"$row\">$n</option>";
       }
    My VB forum: BMWRA

    Comment

    • Karel Souffriau
      Member
      • Jul 2009
      • 30
      • 4.2.X

      #3
      Or:

      PHP Code:
      foreach ( $race as $key => $subArray ) {
          
      $n $subArray[1];
          
          echo 
      "<option value=\"$key\">$n</option>";

      Comment

      widgetinstance 262 (Related Topics) skipped due to lack of content & hide_module_if_empty option.
      Working...