1
\$\begingroup\$

I'm a PHP newbie and I have a question. Is there a better way to do this? A nice solution?

$list = isset($_GET['list']) ? htmlspecialchars($_GET['list']) : "experience";

<select name="type" id="type">
<option value="experience">Experience</option>
<option value="magic"<?=$list == "magic" ? 'selected' : '';?>>Magic Points</option>
<option value="shielding"<?=$list == "shielding" ? 'selected' : '';?>>Shielding</option>
<option value="distance"<?=$list == "distance" ? 'selected' : '';?>>Distance</option>
<option value="melee"<?=$list == "sword" ? 'selected' : '';?>>Melee</option>
<option value="fishing"<?=$list == "fishing" ? 'selected' : '';?>>Fishing</option>
</select>
\$\endgroup\$
1

2 Answers 2

3
\$\begingroup\$

You can use a lookup table for your values like this:

$values = array("magic" => "Magic points", ...);

and then loop over that to reduce the duplication:

foreach ($values as $key => $value) {
    ...
\$\endgroup\$
2
\$\begingroup\$

You might want to build a wrapper for this.

$output->add_select(array $fields, $id, $name, $multichoice = false) {

    $html = "<select name='$type' id='type'>";

    foreach ($fields AS $field){
        $html.=...
    }

    ... 
    return $html;

}

You get the idea. There is nothing more convenient hat having all those form-gruntworks in methods.

$output->add_select($this->get_powers(), 'power', 'power')); or alike and you are good to go.

\$\endgroup\$
1
  • \$\begingroup\$ This might be a bit overkill, but definitely a good way to introduce OP to OOP and compartmentalization. \$\endgroup\$
    – jsanc623
    Commented Jun 6, 2013 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.