Reputation: 4662
Why can't I use variable which contains a number to specify an array value:
$info(array)
$mySQLHeadings(array)
$infoString(empty String)
$mySQLHeadingString(empty string)
for ($i=0; $i<=count($info) ; $i++){
if($info[$i] != ""){
$mySQLHeadingString .= $mySQLHeadings[$i] . ",";
$infoString .= "'". $info[$i] ."',";
}
}
PHP says it's an undefined offset $i in the arrays. How can I correct it or do something similar. Thank you so much.
Upvotes: 0
Views: 85
Reputation: 12717
If $info is numerically indexed, you can access elements with $i, but not further than max index !
count() gives you the array length, but max numeric index is (length - 1)
so :
for ($i=0; $i < count($info); $i++) {
//....
}
Upvotes: 0
Reputation: 17715
You should write for ($i = 0; $i < count($info); $i++)
. Array indexes start from 0 while count()
starts from 1.
Also don't use count()
inside for
loop - move it before:
$count_info = count($info);
for ($i = 0; $i < $count_info; $i++)
Upvotes: 2