NewBie
NewBie

Reputation: 67

Display array list elements in dropdown list in php

For example, I have such array:

$someArray = Array (
    [stationList] => Array (
        [0] => Array (
            [stationName] => A.S.Peta Bypass
            [stationId] => -1 )
        [1] => Array (
            [stationName] => Aala
            [stationId] => -1 )
    )
)

Now U want to display the array elements(stationName) in a dropdown list in php, I used the below code:

<select id="txtLabourId">                                                                                                                          
  <option selected="selected">Choose one</option>

  <?php
    foreach($someArray as $name) { ?>
      <option value="<?php echo $name['stationName'] ?>"><?php echo $name['stationName'] ?></option>
  <?php
    } ?>                                                                                                              
</select>   

But its giving the error:

Undefined index stationName on line 222

How to resolve this? Any help appreciated.

Upvotes: 1

Views: 3474

Answers (4)

Abdallah Salem
Abdallah Salem

Reputation: 1

value type "; echo "$val"; echo "".gettype($val).""; } ?>

Upvotes: 0

Gautam D
Gautam D

Reputation: 330

You should add the inner array stationList into loop.

Your loop code should be like this:

foreach($someArray['stationList'] as $name)

Upvotes: 1

Bananaapple
Bananaapple

Reputation: 3114

You need to give stationList to your foreach, not the wrapping array, so:

foreach($someArray['stationList'] as $name) { ...

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94662

The $someArray array contains another array, so start your foreach loop from the inner array like this

<?php
    foreach($someArray['stationList'] as $station) { 
?>
      <option value="<?php echo $station['stationId'] ?>"><?php echo $station['stationName'] ?></option>
<?php
    } 
?>   

Upvotes: 1

Related Questions