user1881482
user1881482

Reputation: 746

For loop with foreach loop in it? PHP

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

Upvotes: 0

Views: 122

Answers (2)

Francisco Presencia
Francisco Presencia

Reputation: 8858

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.

Upvotes: 0

Kami
Kami

Reputation: 19457

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.

Upvotes: 1

Related Questions