Jump to content

Short circut eval question


tibberous

Recommended Posts

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.

Link to comment
Share on other sites

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?

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.