Boby Boby - 7 months ago 14
PHP Question

Why need "-1" in my For loops php

Good day, Please check my script first.

for($x = 0;$x<=count($outlet);$x++)
{
echo $x." insert into arealeader
(
[Kodearealeader],[OutletCode],[NipLeader],[NipChief],[NipRM],[CutOff],[flag],[CreatedBy],[CreatedDate])
values ('$generatecode[$x]','$outlet[$x]','$leader[$x]','$chief[$x]','$regionalmanager[$x]','$periode','1','$nip_login','$DateNow->time'
)<br>";
}


My problem is when i only insert two outlets from my form. the result will show 3 lines. But it will working fine when i do this
for($x = 0;$x<=count($outlet)-1;$x++)


result

0 insert into arealeader ( [Kodearealeader],[OutletCode],[NipLeader],[NipChief],[NipRM],[CutOff],[flag],[CreatedBy],[CreatedDate]) values ( 'K','CF-LBS','','4141413','9191','','1','1602762','2016-04-29 10:09:56.640' )
1 insert into arealeader ( [Kodearealeader],[OutletCode],[NipLeader],[NipChief],[NipRM],[CutOff],[flag],[CreatedBy],[CreatedDate]) values ( 'L','K-ATR2','','4141413','9191','','1','1602762','2016-04-29 10:09:56.640' )
2 insert into arealeader ( [Kodearealeader],[OutletCode],[NipLeader],[NipChief],[NipRM],[CutOff],[flag],[CreatedBy],[CreatedDate]) values ( '0','','','','','','1','1602762','2016-04-29 10:09:56.640' )


echo count($outlet)
result is
2

Answer

You are initializing x to 0. Then executing echo once with x in this state. x then increments to 1. 1 is still less than or equal to 2, so the echo runs again. x increments again to 2, which is still less than or equal to 2, so the echo executes a third time. What you probably want to do is replace $x<=count($outlet) with $x<count($outlet), as you really want 'less than', not 'less than or equal to' for running a loop once for each index in a zero-indexed array.