Hi all and thanks for reading. I came accross a function on the internet for creating a <select> box out of an array. I understand all of the code except for a few things:

<?php
function dropdown($name, array $options, $selected=null) {

  // Begin the select tag.
  $dropdown = "<select name=\"$name\" id=\"$name\">\r\n";

  $selected = $selected;

  // Loop over all the options.
  foreach ($options as $key=>$option) {
    // Assign a selected value.
    $select = $selected==$key ? " selected" : null;

    // Add each option to the dropdown.
    $dropdown .= "<option value=\"$key\"$select>$option</option>\r\n";
  }

  // Close the select tag.
  $dropdown .= "</select>\r\n";

  // Return the completed dropdown.
  return $dropdown;
}
?>
<form>
<?php
$name = "dropDown";
$options = array( "dingo", "wombat", "kangaroo" );
$selected = 2;
echo dropdown($name, $options, $selected);
?>
</form>

1) What is the purpose of typing this: "$selected = $selected;" when the name tag did not need to be rebound?

2) "foreach ($options as $key=>$option) {" What is $key?

3) "$select = $selected==$key ? " selected" : null;" can someone break that down to me in plain english?

Thank you very much for reading,


Anthony

I executed this program to my knowledge i found the following things to be change

Remove array from function definition,and keep paranthesis for $select =( $selected==$key ? " selected" : null);


The option "$selected = $selected;" means the key value which is equal to the options passed in array will be in selected position.

Key refers to the index of an array as you passed options as an array we want to parse that array for that purpose we use key and value keywords.

Hi and thanks for replying!

Key refers to the index of an array as you passed options as an array we want to parse that array for that purpose we use key and value keywords.

So the $key->$option is taking the reference key of the specific part of the array? i.e.

$key->option could also be 1->shellfish ?

When referencing an array in this fashion, must I always write $key->$option or could I just write $option?


As for the $select = $selected==$key ? " selected" : null; part, is this just the same as writing:

if ($selected == $key) {
  $select = " selected";
} else {
  $select = NULL;
}

Thanks,


Anthony

The alternate code is nothing but the you specified instead of that it is one line code.

I forgot to say $option should be replaced by $value

Thanks very much for your help. Everything works fine, without using $value so I'll leave it as option!

I'll also stick to my slightly larger if statement than that shorthand method with the question mark, it confuses me so best to avoid it!

This question has already been answered. Start a new discussion instead.