tibberous Posted March 2, 2010 Share Posted March 2, 2010 I am looping through an array called items: for($i=0;$item=$items[$i];$i++){ // I want to see the price of the next item, if there is a next item if($item[$i+1] && $item[$i+1]['price'] ... Does php look at this, evaluate $item[$i+1] to false, then leave because the condition can never be true? Is $item[$i+1] guaranteed to get evaluated first because it is the left most condition? Is this a standard way to write code, or would 2 if's be better? if($item[$i+1]) if($item[$i+1]['price']) // safe, but makes it look like I don't understand Short circuit evaluation. Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted March 2, 2010 Share Posted March 2, 2010 The only thing that affects how the for(){} loop operates are the three expressions - The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop. In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends. At the end of each iteration, expr3 is evaluated (executed). Note: $item=$items[$i] sets $item equal to $items[$i] and tests if the result of that assignment is true. Is that what you intend? Quote Link to comment Share on other sites More sharing options...
tibberous Posted March 2, 2010 Author Share Posted March 2, 2010 Yeah - that's what I want it to do. The code was originally a foreach loop I rewrote so I could peek ahead. The second line, the if(), is what I was asking the question about. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.