error generating dynamic html

hi there!
i’m learning php, and this code snippet should dynamically load all the checkboxes, and mark those which were previously marked when the submit button was pressed. it loads perfectly, but after I set which checkboxes should be marked next time, the same page loads again, nothing marked. please help :slight_smile:
[php]

<?php function generate_checkboxes($name, $options, $default=array()) { if (!is_array($default)) $default = array(); foreach($options as $value => $label) { $html .= ""; $html .= $label . "
"; } return($html); } $options = array("movies" => "Going to the movies", "music" => "Listening to music", "sport" => "Playing or watching sports", "travel" => "Traveling"); $html = generate_checkboxes("interests", $options, $interests); ?>

Please select your interests

<?php print $html;?> [/php]

Hi, this should work for you. The script now gets the value of the POST and then for each checkbox it checks to see if the value is in the POST array. Take a look and hope you understand what has been added.

[php]

<?php function generate_checkboxes($name, $options, $default=array()) { $name = "interests"; $results = $_POST['interests']; if (!is_array($default)) $default = array(); foreach($options as $value => $label) { $html .= ""; $html .= $label . "
"; } return($html); } $options = array("movies" => "Going to the movies", "music" => "Listening to music", "sport" => "Playing or watching sports", "travel" => "Traveling"); $html = generate_checkboxes("interests", $options, $interests); ?>

Please select your interests

<?php print $html;?> [/php]

apologies, you can take out the
[php]$name = “interests”;[/php]
from the script above, I added that for testing reasons

thank you for your help, that was the problem, the array ‘interests’ didn’t get passed to the function, it always got an empty array. so any data that I want to access from the post should be done with this $_POST[‘nameofvariable’] method. I thought if I simply use the name of the variable I will get it, and that’s what my book says too. the example was from the book too. anyway thanks again!

Sponsor our Newsletter | Privacy Policy | Terms of Service