2

How can I use a php array as the value of an HTML <option>?

e.g.

<select name='myname'>
  <option value=' array("font-family" => "font-family: 'Yeseva One', serif","font-name" => "Yeseva One","css-name" =>"Yeseva+One")'>
    Font 1
  </option>
  ...
</select>
1
  • eeee... this is not even a valid PHP, are you aware? Commented Dec 10, 2011 at 16:10

4 Answers 4

4

It kind of depends on what you want to archive in the end. I've got 3 options for you:

1) Json is pretty flexible:

<option value="<?php json_encode($yourArray) ?>">Font 1</option

You can then later on convert Json back to an array with json_decode.

2) If you need the data for server client side scripting, it would probably be a better idea to use HTML5's data attributes:

<option value="value1" data-fontname="Yeseva One" data-cssname="Yeseva+One">Font 1</option>

3) You can use hidden input fields, which will allow you to retrieve the values like $_POST['font1']['css_name'] ect. :

<input type="hidden" name="font1[font_name]" value="Yeseva One" />

You will obviously have to escape your values. But you get the idea.

Sign up to request clarification or add additional context in comments.

Comments

2

I think the best approach for you is to put the values with comma separation i.e

<select name='myname'>
<option value='Yeseva One, serif'</option>
</select>

and in the php you can implode the result into an array

$array_of_results = implode( $_POST['myname'] );

1 Comment

i'm not sure it's that i m looking for. I want to use the value like this after : $_POST['myname']['font-name']
1

I think you can serialize the array:

<?php

$arrYourArray = array(
"font-family" => "font-family: 'Yeseva One', serif",
"font-name" => "Yeseva One",
"css-name" =>"Yeseva+One");

?>

<select name="myname">
  <option value="<?php echo serialize($arrYourArray); ?> ">
    Font 1
  </option>
  ...
</select>

Comments

0

Are you trying to create a select form based on the options you have set in your array?

If so, you could do this:

<select name="myname">

    <?php

    $selects = Array('Verdana' => 'font-family: Verdana;', '\'Trebuchet MS\', Helvetica, Arial, sans-serif' => 'font-family: \'Trebuchet MS\', Helvetica, Arial, sans-serif;');

    foreach($selects as $select => $css) {

        echo '<option value="' . $css . '">' . $select . '</option>';

    }

    ?>

</select>

1 Comment

No, for exemple : <select> <option value=array( "x" => "123", "y" => "666", "z" =>"987")> </option> <option value=array( "x" => "344", "y" => "545", "z" =>"543")> </option> </select> In php, i want to access to [y] from my value

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.