Wednesday 15 February 2012

php - for loop -- ununderstandable behavior -



php - for loop -- ununderstandable behavior -

i have have these for loops:

for ($x = 0; $x<2;$x++){ $allproducts = array(); ($y = 0; $y<105;$y++) { //<<<<<<<<<<<<< (105) number mean $allproducts[] = 'test'.$y; } echo "<pre>"; echo "allproducts 0 -- "; var_dump($allproducts); echo "</pre>"; ($i = 0; $i < count($allproducts); $i++) { $result = array_slice($allproducts, 0, 20); echo "<pre>"; echo "result -- "; var_dump($result); echo "</pre>"; $allproducts = (array_diff($allproducts, $result)); echo "<pre>"; echo "allproducts 1 -- "; var_dump($allproducts); echo "</pre>"; }}

in real code (here:)

for ($x = 0; $x<1;){ $allproducts = array(); $abfrage = "select sku skulist"; if ($result = $sql->query($abfrage)) { while ($row = $result->fetch_assoc()) { $allproducts[] = $row['sku']; } } ($i = 0; $i < count($allproducts); ++$i) { $result = array_slice($allproducts, 0, 20); $allproducts = (array_diff($allproducts, $result)); //.... more code }}

...i take info db instead of loop:

$allproducts = array(); ($y = 0; $y<105;$y++) { //<<<<<<<<<<<<< (105) number mean $allproducts[] = 'test'.$y; }

but changed show/ easier reconstruction.

the behavior same:

when have 105 entries in array, don't empty array output

echo "allproducts 1 -- "; var_dump($allproducts);

which desired behavior.

when alter 105 (eg.) 65, outputs empty arrays

allproducts 1 -- array(0)

at end of sec nested loop:

for ($i = 0; $i < count($allproducts); $i++) {

now have three problems:

why happen? don't difference how can achieve, there no empty array @ end? (stops programs work) i need 20 values in every $result array

for ($i = 0; $i < count($allproducts); $i++) { // ... $allproducts = (array_diff($allproducts, $result));

you changing $allproducts array while going through it! how can expect work reliably then?

instead, try:

foreach( $allproducts $i => $product)

although must admit i'm not sure you're trying do.

php arrays for-loop

No comments:

Post a Comment