user10701881
user10701881

Reputation:

PHP & MySQL - Populate Select Dropdown using Arrays

I'm trying to populate my dropdown using an array on another page so here is what I've got I need to populate my dropdown select a list of nationalities, so far I've got an array of list of nationalities but I cannot populate the select box on the array.

on my fetch.php

I've got

<?php include('nationality.php') ?>

<select id="register-nationality" name="registerNationality" required data-msg="Please select your Nationality" class="form-control">

                    <option>Select Nationality</option>

                    <?php 

                    foreach ($nationality as $national) {
                      echo "<option value='$nationals'>$nationals</option>";  
                    }

                     ?>

                  </select> 

and in the nationality.php here is where I got the list of nationalities and it is an array.

so here is a sample of the code it is too long so I will give you the sample

    <?php 

$nationals = array(
        'Afghan',
        'Albanian',
        'Algerian',
        'American',
        'Andorran',
        'Angolan',
        'Antiguans',
        'Argentinean',
        'Armenian',
        'Australian',
        'Austrian',
        'Azerbaijani',
        'Bahamian',
        'Bahraini',
        'Bangladeshi',
        'Barbadian',
        'Barbudans',
..
..
..  and so on

);

 ?>

and so nothing is showing.

Upvotes: 1

Views: 143

Answers (2)

Yogendrasinh
Yogendrasinh

Reputation: 895

Yor foreach variable is $nationals and not $nationality. you have used $nationals which is not defined. your variable name is $national. in your loop change as echo "<option value='$national'>$national</option>";

$nationals = array(
    'Afghan',
    'Albanian',
    'Algerian',
    'American',
    'Andorran',
    'Angolan',
    'Antiguans',
    'Argentinean',
    'Armenian',
    'Australian',
    'Austrian',
    'Azerbaijani',
    'Bahamian',
    'Bahraini',
    'Bangladeshi',
    'Barbadian',
    'Barbudans',
);

foreach ($nationals as $national) {
  echo "<option value='$national'>$national</option>";  
}

Upvotes: 0

Juan J
Juan J

Reputation: 413

Change your include statement to : include_file "nationality.php";

The name of your array is $nationals. You can't use $nationality because it doesn't exists.

Change your code to the following:

foreach($nationals as $national){
    echo "<option value='$national'>$national</option>";
}

Upvotes: 1

Related Questions