Kevin
Kevin

Reputation: 33

Create select option using a php array and php foreach

I am working with a html select dropdown list <select></select> in php. I can create my dropdown lists fine as long as they hold just a single value but i am struggling to create the dropdown list if i need a value and a display value, where the value needs to be the id of a hospital and the display value being the hospital name. I am fairly new to php and feel the solution here is just out of my grasp. What i need is below result seen in image 2 but when hospital name is selected it is actualu storing the hospital id. Can someone please assist.....many thanks

Image2

...foreach($records as $record)
            {
                  $dataValues[] = $record->getField('hospitalId');
                  $dataValues[] = $record->getField('hospitalName');            
            }

foreach($dataValues as $vl)
            {
                  $output .= '<option value="' . $vl[0] . '">' . $vl[1] . '</option>';
            }
echo $output;...

Upvotes: 0

Views: 263

Answers (2)

symcbean
symcbean

Reputation: 48357

foreach ($records as $record) {
    $output .= '<option value="' . (integer)$record->getField('hospitalId') . '">' 
     . htmlentities($record->getField('hospitalName')) 
     . "</option\n";
}

Upvotes: 0

You can use the key and the value to complete the dropdown.

$output=' <!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>Select box with a placeholder</h2>
    <select name="hospital" required>';
    foreach($records as $record)
            {
                  $dataValues[$record->getField('hospitalId')] = $record->getField('hospitalName');

            }

foreach($dataValues as $id=>$name)
            {
                  $output .= '<option value="' . $id . '">' . $name . '</option>';
            }

$output .= '</select>
  </body>
</html>';
echo $output;

so, i didn't see where you open o close de select tag Here is the html documentation: https://www.w3docs.com/snippets/css/how-to-create-a-placeholder-for-an-html5-select-box-by-using-only-html-and-css.html

Upvotes: 1

Related Questions