0

I'm trying to code a script that allows you to generate a with the cities of each country. Cities should be grouped by country through PHP array.

So this example here, in HTML, it is what I wanted but in PHP Array.

<select>
    <optgroup label="Country X">
        <option value="City1">City 1</option>
        <option value="City2">City 2</option>
        <option value="City3">City 3</option>
        <option value="City4">City 4</option>
        <option value="City5">City 5</option>
    </optgroup>

    <optgroup label="Country Y">
        <option value="City6">City 6</option>
        <option value="City7">City 7</option>
        <option value="City8">City 8</option>
        <option value="City9">City 9</option>
        <option value="City10">City 10</option>
    </optgroup>

    <optgroup label="Country Z">
        <option value="City11">City 11</option>
        <option value="City12">City 12</option>
        <option value="City13">City 13</option>
        <option value="City14">City 14</option>
        <option value="City15">City 15</option>
    </optgroup>
</select>

Here's the code what I've done so far with PHP... The main problem of this one is each country has all the cities. I only wanted 5 cities each in different countries.

<?php

$countries = array(
    'Country X',
    'Country Y',
    'Country Z', 
);

$cities = array(
    'City 1',
    'City 2',
    'City 3', 
    'City 4',
    'City 5', 
    'City 6',
    'City 7',
    'City 8', 
    'City 9',
    'City 10', 
    'City 11',
    'City 12',
    'City 13', 
    'City 14',
    'City 15', 
);


?>

<select name="places">
<?php foreach($countries as $key): ?>
        <optgroup label="<?php echo $key; ?>">
        <?php foreach($cities as $key => $value): ?>
            <?php echo '<option value="'.$key.'">'.$value.'</option>'; ?>
            <?php endforeach; ?>
        </optgroup>
<?php endforeach; ?>
</select>
2
  • 1
    Format your array as $arr = [ 'country 1' => ['City 1', 'City 2'], 'country 2' => ['City 1', 'City 2'] ] instead. This way you can see exactly which city "belongs" to which county. Commented Sep 24, 2019 at 8:23
  • Print option tags with optgroup tags from a sorted 2d array Commented Oct 31, 2024 at 10:29

1 Answer 1

1

Split cities in chunks:

$cities = array_chunk($cities, 5);
$counter = 0;?>

<select name="places">
<?php foreach($countries as $key): ?>
        <optgroup label="<?php echo $key; ?>">
        <?php foreach($cities[$counter++] as $key => $value): ?>
            <?php echo '<option value="'.$key.'">'.$value.'</option>'; ?>
            <?php endforeach; ?>
        </optgroup>
<?php endforeach; ?>
</select>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.