Reusable Drop-down with for loop function

Posted By: Ian on Feb 17, 2014 in PHP, Snippets
Last modified on January 29th, 2015 at 9:31 pm,

I had 5 drop-down lists that all involved numbers that were pulled from a database and originally if i wanted one to go from 1-20 I’d have to write it 20 times! That’s not good coding and takes longer when editing too so now i wrote this which does what i want and might be useful to you too.

If you just want say drop-down to go from 0-20 that’s fine but i always wanted 2 to go in multiples of 3 and 5 which is why the last parameter $multiplier is set to null by default and only if it is set will it be used.

<?php
function doDropdown($name, $start, $end, $dbv, $multiplier = null)
{
$dd = '<select name="' . $name . '" id="' . $name . '">';
for ($i = $start; $i <= $end; $i++) {
if (!$multiplier) {
$dd .= '<option value="' . $i . '"' . ($dbv == $i ? ' selected="selected"' : '') . '>' . $i . '</option>';
} elseif ($i % $multiplier == 0) {
$dd .= '<option value="' . $i . '"' . ($dbv == $i ? ' selected="selected"' : '') . '>' . $i . '</option>';
}
}
$dd .= '</select>';
return $dd;
}
?>

 

Syntax

echo doDropdown("NAME", "START", "END", $DBV, "MULTIPLIER");

 

Parameters:

  1. NAME: Name and id of drop-down list
  2. START: Starting number
  3. END: End number
  4. DBV: Selected value from database
  5. (Optional) MULTIPLIER: Only print multiple of this number until END is reached

 
Examples of use

echo doDropdown("timeLock", "0", "30", $dbTimeLock, "2");
echo doDropdown("connections", "3", "7", $dbconnections);

 
Try Me

 

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125