Jump to content

The logic seems sound, but breaks my select.


skania

Recommended Posts

I need a list for a form that will be used to register children to their legal guardian. The list is a drop down menu, which will eventually be sorted alphabetically, if php can do that :D. However, the current problem is that there are single parents out there, way current way the code is set up works, but it looks off when there is a random '&' with no second parent name. When I try to do a ternary operation, it completely stops all options from appearing from the drop down.

 

Here is the code that WORKS:

echo "<option value=" . $row_list["parentID"] . ">" . $row_list["parentOneFirstName"] . "  " . $row_list["parentOneLastName"] . "    &    " . $row_list["parentTwoFirstName"] . " " . $row_list["parentTwoLastName"] . "</option>";

Here is the code with the ternary operation:

 echo "<option value=" . $row_list["parentID"] . ">" . $row_list["parentOneFirstName"] . "  " . $row_list["parentOneLastName"] . ((!empty($row_list["parentTwoFirstName"])) and (!empty($row_list["parentTwoLastName"]))) ? "    &    "  . $row_list["parentTwoFirstName"] . " " . $row_list["parentTwoLastName"] . "</option>" : "</option>";

Anyone know what the problem is, or even better, how to fix it? I appreciate any and all input, thank you.

For one thing, you should use && not "and".

 

Your code is very hard to read the way you have it, plus it's invalid HTML. Let's clean it up. You kind of have your use of quotes backwards too. In PHP "" is a interpolated string, and '' is not. Use '' when you don't have variables inside the string.

<?php
$value = $row_list['parentID'];
$text = $row_list['parentOneFirstName'] . '  ' . $row_list['parentOneLastName'];
if(!empty($row_list['parentTwoFirstName'])){ // If the first name is empty, would the last name ever have a value? If so, add your && in here.
   $text .= ' & '.$row_list['parentTwoFirstName'] . ' ' . $row_list['parentTwoLastName'];
}
echo '<option value="' . $value . '">' . $text . '</option>';
You could make it even easier and cleaner by putting the parents names into an array when you get the info from the database, and using implode. It would look something like this.

<?php
$value = $row_list['parentID'];
$text = implode(' & ', $row_list['parents_names']);
echo '<option value="' . $value . '">' . $text . '</option>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.