0

I am trying to make the following happen.

Go through a for loop and produce a set of 7 select boxes with time options in them. I have this loop working fine right now. This is for a form with times for start of an event for each day of the week.

On user wanting to change the values, I would like to produce the same 7 boxes however foreach of the values entered in the database I would like to add the original selected value for that date, and provide the please select value for the of the boxes.

foreach loop for the times

foreach ($times as $time) {
    echo '<option value="' . $time['num'] . '"'; if ($event == $time['dec']){echo 'selected="selected"';};
            echo '>';
            echo $time['clock'];
            echo '</option>';
}

Times Array

$times = array( array('num' => 70000, 'dec' => '07:00:00', 'clock' => '7:00am'), array('num' => 71500, 'dec' => '07:15:00', 'clock' => '7:15am') etc…

This produces the select options.

Then the foreach to get the existing values.

foreach ($event -> Selected as $select) {
   $event = $select -> Start;
}

This is all working right now but only produces say 3 selects if 3 records exist, I would like to produce 7 selects with the first 3 selects with the DB value, if 3 records exist and 4 empty selects

1
  • Have you tried to do $times = array_merge($times, array_fill(0, 7-count($times))); just before your foreach() for creating exactly 7 elements? Commented Jan 24, 2014 at 17:57

2 Answers 2

1

The array contains only a limited number of entries, so the loop will iterate only up to this number.

You can work around this by checking how many elments are in the array, and outputting empty values for the rest.

for example add the following after the loop:

$count = 7 - count($times);
for($i = 0; $i < $count; $i ++)
{
    echo '<option></option>';
}

The above is a simple loop that outputs empty entries to ensure there are 7 drop down values.

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

Comments

0

You can do this before your foreach:

$desired = 7;
$extra = array_fill(0, $desired - count($times));
$times = array_merge($times, $extra);

It will make your array $times to be always as long as the number in $desired.

Comments

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.