-1

Sorry if this is too obvious but I’m learning how to deal with arrays and I’m totally stuck, cannot go on :(

Having the following array:

$myarray: array =
0:array=
 0:string=-
 1:string=-
1:array=
 0:string=AA1
 1:string=Book title 1
 2:string=Author 1
2:array=
 0:string=AA2 
 1:string=Book title 2
 2:string=Author2
.
.

I need to build a select in an html form filling it in this way:

<select id="bookTitles">
<option value="-" selected="selected">Select..</option>
<option value="AA1"> Book title 1</option> 
<option value="AA2"> Book title 2</option> 
.
.
   </select>

How can I loop the $myarray to do so?

Thanks a ton!

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
Miguel Mas
  • 547
  • 2
  • 6
  • 23
  • 1
    The syntax doesn't look like PHP. – flowfree Jun 06 '12 at 15:18
  • @bsdnoobz I think he just doesn't know about print_r() and is trying to represent the array structure. – HappyTimeGopher Jun 06 '12 at 15:21
  • [`foreach`](http://php.net/manual/en/control-structures.foreach.php), [`for`](http://www.php.net/manual/en/control-structures.for.php) or [`while`](http://www.php.net/manual/en/control-structures.while.php) ... this is a question for the manual, probably not Stack Overflow. –  Jun 06 '12 at 15:22

2 Answers2

1

Try this:

<select name = "theSelect">
<option value = "-" selected = "selected">Select...</option>
<?php
    array_shift($myarray); // take off the first element that is empty
    foreach( $myarray as $k => $v) {
        echo('<option value = "' . $v[0] . '">' . $v[1] . '</option>');
    }
?>
</select>
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
0
<select id="bookTitles">
    <option value="-" selected="selected">Select..</option>
    <?php foreach ($myarray as $value) : ?>
        <option value="<?php echo $value[0]; ?>"> <?php echo $value[1]; ?></option> 
    <?php endforeach; ?>
</select>

A few notes:

  • I'm using foreach() to loop through the array
  • I use : and endforeach; instead of { and } because it generally looks cleaner when ouputting HTML
  • I add the default option before the loop because... well, why not?
  • Alternatively, you can use shorttags, like this: <?=$value[0]?> (read more on this here)
Community
  • 1
  • 1
Jeroen
  • 13,056
  • 4
  • 42
  • 63