mpavlovic89
mpavlovic89

Reputation: 769

PHP Array within the for loop

Is there a way to create an array within the for loop. There are several similar answers here, but none of them or the logic from these answers is applicable in the code below.

for($j=1;$j<6;$j++) {
    $odg[$j] = "";
}
//the rest of the code which gives values to the array elements (outside the loop)

This is how array should look like before insert it into the sql query.

$odg_ids = array($odg[1],$odg[2],$odg[3],$odg[4],$odg[5]);
$odg_list = implode("','", $odg_ids);

This is the for loop that should generate an array.

for($i=1;$i<6;$i++) {
    $odg_ids[] = $odg[$i];
    $odg_list[] = implode("','", $odg_ids[$i]);
}

Something's missing?

Upvotes: 1

Views: 56

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

You need to do the implode after the loop. Otherwise you keep appending to odg_list each time.

for ($i=1;$i<6;$i++) {
    $odg_ids[] = $odg[$i];
}
$odg_list = implode("','", $odg_ids[$i]);

I'm not sure where you get 6 from, but you could also use array_slice to get the 1st through 6th elements (you are omitting the 0th element).

Upvotes: 5

Related Questions