0

I was wondering if someone could help me. I want to iterate through an associative array and put the results into two combo boxes. The combo boxes will have the exact same data in each other.

while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
    echo "<option value='" . $this->result['id] . "'>" 
               . $this->result['name'] . "</option>";
}

Do I have to run this loop twice for 2 seperate comboboxes or is there a more efficient way of doing this?

1
  • Use a collecting variable instead of echoing the HTML. Commented Jul 2, 2013 at 22:50

3 Answers 3

2

Your best bet in this situation is to just accumulate the text in a string and echo it out twice.

$options = "";
while ($this->results = $this->dbhandle->fetch(PDO::Fetch_Assoc))
{
    $options.= "<option value='" . $this->result['id] . "'>" 
               . $this->result['name'] . "</option>";
}

echo "<select name='combo1'>".$options."</select>";
echo "<select name='combo2'>".$options."</select>";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I feel like I have should of thought of this on my own. I appreciate everyone's response.
0

How about something like this (raw code to give you an idea):

while
{
    $combo_options .= "<option>" ....// rest of your code
}

Then print the variable inside your selects:

<select id="combo1"><?=$combo_options?></select>
<select id="combo2"><?=$combo_options?></select>

Comments

0

You can capture the output as a variable and then echo it as needed

while ($this->results = $this->dbhandle->fetch(PDO::FetchAssoc)){
     $output .= "<option value='" . $this->result['id'] . "'>" . $this->result['name'] . "</option>";
}

/// later on in your script

print $output;

1 Comment

Think you mean to append to $output instead of overwrite each time

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.