I have seen many similar issues but none that can help explain my issue. I have an array called cities, with a nested array for the state that has the cities of that state. It looks like this:
$cities = array(
"ca" => array(
"los-angeles" => "Los Angeles"
),
"wa" => array(
"bellingham" => "Bellingham",
"seattle" => "Seattle",
"tacoma" => "Tacoma"
)
);
My PHP code to display many HTML select
fields:
<?php
foreach ($cities as $state) {
echo "<select name='city' id='" . $state . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
?>
The id
of the select
is always Array
. How can I use the key, like "ca" or "wa"?
The problem is that you should be using the array key for the select on the states. Here is my revision of your code. Note that I explicitly have named state_key
and state_value
as well as city_key
and city_value
. Naming things explicitly like this helps in debugging. I also added a closing </select>
element so the content renders correctly.
foreach ($cities as $state_key => $state_value) {
echo "<select name='city' id='" . $state_key . "'>";
foreach ($state_value as $city_key => $city_value) {
echo "<option value='" . $city_key . "'>" . $city_value . "</option>";
}
echo "</select>";
}
Try uisng echo "<select name='city' id='" . $state['los-angeles'] . "'>";
instead of echo "<select name='city' id='" . $state . "'>";
If you want ca
as your select element id then use below one,
foreach ($cities as $key=>$state) {
echo "<select name='city' id='" . $key . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
If you want like los-angeles
as id of your select element, then use below one
foreach ($cities as $key=>$state) {
$SelectId = strtolower(str_replace(" ",'-',$state['los-angeles']));
echo "<select name='city' id='" . $SelectId . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
That's because the first foreach loop is going over an array of arrays. So each member is going to be an array. If you had id ='" . $state[0]
you would see the first member of said array.
the var_dump
function is your friend.
You could get all the cities by using array_keys
function.
foreach ($cities as $key=>$state) {
echo "<select name='city' id='" . $key . "'>";
foreach ($state as $city => $name) {
echo "<option value='" . $city . "'>" . $name . "</option>";
}
}
change to this
in your case $state is an array containing cities. so it is always showing the value as Array().