0

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.

2 Answers 2

2

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++)
Sign up to request clarification or add additional context in comments.

Comments

0

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++) {
    //....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.