开发者

calling function in for and foreach loop failing in PHP

开发者 https://www.devze.com 2023-03-28 03:18 出处:网络
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.

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 th开发者_运维问答e 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>';


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>';


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);`


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>';

}


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>';
0

精彩评论

暂无评论...
验证码 换一张
取 消