2

I have an array on which I am iterating using for loop. The array has URL at each element that is needed to be passed as argument to a function.

When I call the function during iteration, loop stops after first iteration and does not proceed over entire array.

When I try to echo out only the value in array and does not call function in loop then it works fine.

This is the same issue if I use foreach loop. Please help.

Here is my code

echo '<ol>';
for($i=0; $i < count($watchList); $i++){
    saveProduct(getProductDetail($watchList[$i]));
    echo ' <li>Product Saved '. $watchList[$i] .'</li>';
}
echo '</ol>';
4
  • What is the value of count($watchList)? Commented Aug 13, 2011 at 20:43
  • Do saveProduct or getProductDetail modify $watchList in any way? Commented Aug 13, 2011 at 20:45
  • 288 items if i comment the function call and only echo out the following line after function I see all the iterations outputed. Commented Aug 13, 2011 at 20:46
  • getProductDetail is returning an array and saveProduct is executing SQL on MySql DB. saveProduct takes argument of associative array. Commented Aug 13, 2011 at 20:47

4 Answers 4

2

It's possible that the array is not sequential. You're assuming that it goes from 0-n, but that might not be the case. Use this and it should work:

echo '<ol>';
foreach($watchList as $key=>$watchItem){
    saveProduct(getProductDetail($watchItem));
    echo ' <li>Product Saved '. $watchItem .'</li>';
}
echo '</ol>';
Sign up to request clarification or add additional context in comments.

Comments

1

No problem with the loop. Must be something wrong with the functions you're calling.

Try turning on error reporting if you haven't already.

ini_set(‘error_reporting’, E_ALL);
ini_set(‘display_errors’, 1);`

Comments

1
error_reporting(E_ALL );
ini_set('display_errors', '1');

Add code above to your code to see what's wrong?

foreach($watchList as $value){
    saveProduct(getProductDetail($value));
    echo ' <li>Product Saved '. $value .'</li>';

}

1 Comment

the astonishing thing is that in result of first iteration the data get saved in db but loop fails
0

It's because your array key is not matching the value of $i in each iteration of the loop, presumably because your array keys are not sequential integers. No doubt the output (when you take the function call out) just prints 'Product Saved' as the $watchList[$i] is NULL.

You are simply trying to pass the value in the array to that function, so do it as follows and it won't matter what the keys are;

echo '<ol>';
foreach($watchlist as $key => $item){
    saveProduct(getProductDetail($item));
    echo ' <li>Product Saved '. $item .'</li>';
}
echo '</ol>';

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.