Search code examples
phphtmlfor-loopdropdown

PHP ECHO table with dynamic dropdown as one column using FOR EACH


I am a bit stuck I am attempting to build out a table with HTML and PHP. Ok got that done. Now I want to add a dynamic dropdown as one of the column options but cant seem to figure out how to mix the PHP, the HTML and the needed FOR EACH loop.

I know its currently wrong but am posting a variable of what I have been trying below.

    echo '<td>' . "<select>". "<option value =" . $sf_name . '&nbsp;'. $sl_name . ">" . $sf_name . '&nbsp;'. $sl_name . "</option>" .
    foreach($Staff_On_Duty as $person){         
  "<option value =" . $sf_name_option=$person->Staff_First_Name . '&nbsp;'. $sl_name_option=$person->Staff_Last_Name . ">" . $sf_name_option . '&nbsp;'. $sl_name_option . "</option>" 
    }
    . "</select>" .'</td>';

I need to have the currently selected individual at the top of the dropdown with the option to change that person out. the first .sf_name comes from higher in the code and gives me the name of the individual currently selected. The foreach runs from the $Staff_On_Duty query to give me everyone working right now. What is the right way to do this?


Solution

  • This is how I would do it, essentially only fill the dropdown and mark the option that should have been selected (other stuff is a matter of preference):

    echo("<td><select>");
    foreach($Staff_On_Duty as $person){         
        $sf_name_option=$person->Staff_First_Name; // separated for clarity, you could also use $person->Staff_First_Name everywhere
        $sl_name_option=$person->Staff_Last_Name;
        echo("<option value = $sf_name_option&nbsp;$sl_name_option");
        if (($sf_name_option == $sf_name) && ($sl_name_option == $sl_name)) echo (" selected"); // this is the relevant part, but make sure variable values match!
        echo(">$sf_name_option&nbsp;$sl_name_option</option>"); 
    }
    echo("</select></td>");
    

    Note that I did not put any quotation marks cause I have no idea what your variables entail, but it would need them if you don't have them in yet, i.e.:

    ... value=\"$sf_name_option&nbsp;$sl_name_option\" ...