Jump to content

Add html code to php variable


ttmt_101
Go to solution Solved by requinix,

Recommended Posts

Hi all
 
I want to create a simple html select menu from an array like:
 
<select>
  <option value="">Red</option>
  <option value="">Green</option>
  <option value="">Blue</option>
</select>

I know I can output this like:

$my_Arr = array('Red','Green','Blue');


echo "<select>"; 

for($i=0; $i<count($my_Arr); $i++){
  
  echo"<option>".$my_Arr[$i]."</option>";
    
}

echo "</select>";

But I would like to add the select menu to a variable and use later.

 

So I can start the variable off like:

$select_menu = "<select>";

But how can I add the rest of the html code to the variable as it's created, so I end up with:

$select_menu = "<select>
  <option value="">Red</option>
  <option value="">Green</option>
  <option value="">Blue</option>
</select>"
Link to comment
Share on other sites

  • Solution

Append to the string, like

$select_menu = "<select>";
$select_menu = $select_menu . "<option value=''>Red</option>";
$select_menu .= "<option value=''>Green</option>"; // .= is shorthand for the above
$select_menu .= "<option value=''>Blue</option>";
$select_menu .= "</select>";
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.