Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic select array in PHP

Tags:

javascript

php

I have a standard form array in PHP like this. I need to account for up to 10 hours of labor in 15 minute increments with 10 as a value for every 15 min or 40 per hour. Is it possible to automate this into some sort of array with PHP instead of hardcoding each of these values? It just seems like there should be a better way and I have no idea how to start?

<select size="1" name="labor" id="labor">
    <option value="80">2 Hours</option>
    <option value="70">1 Hour 45 min.</option>
    <option value="60">1 Hour 30 min.</option>
    <option value="50">1 Hour 15 min.</option>
    <option value="40">1 Hour</option>
    <option value="30">45 Minutes</option>
    <option value="20">30 Minutes</option>
    <option value="10">15 Minutes</option>
</select>
like image 703
Rocco The Taco Avatar asked Jun 25 '12 21:06

Rocco The Taco


2 Answers

Probably easiest to hardcode the solution. I think this is one of those situations where it is OK as @Wrikken mentioned, as it makes the code very clean and easy to maintain (Imagine coming back to this in a year or two). In addition this situation can also be handled very well with a database table.

First use an array to store you values and descriptions:

$list = array();
$list['10'] = '15 Minutes';
....

Then loop through the entire array to generate your dropdown:

<select size="1" name="labor" id="labor">
<?php
   foreach($list as $value => $desc){
     $option = "<option value=$value>" . $desc . "</option>";
     echo $option;
   }
?>
</select>
like image 185
David Cheung Avatar answered Sep 21 '22 15:09

David Cheung


You need two values, the 10-units increment and the user-displayed value. Run a for loop over $i (or some other variable) from 1 to 40 and calculate your values inside the loop:

  • 10-increment is easy, just multiply $i by ten.
  • For the displayed value, multiply by 15 to get the total amount of minutes. Then transform that into hours and minutes using the modulo operator (which gives you the minutes) and standard divison (to get the hours).
like image 43
Emil Vikström Avatar answered Sep 21 '22 15:09

Emil Vikström