PHP Cape Town Conference

Voting

Please answer this simple SPAM challenge: min(zero, one)?
(Example: nine)

The Note You're Voting On

rlynch at lynchmarks dot com
9 years ago
And, further...

<?php
    $intSize
= sizeof($arrData);

    for(
$i = 0; $i < $intSize; $n++) {
      
// Do stuff
   
}
?>

Can be shortened even further by using the often overlooked 'decrement until zero' concept.  I don't much like decrementing to get a job done, but it can make a lot of sense when the evaluation-of-doneness is time-costly:

<?php
   
for($i = sizeof($arrData); $i-- > 0 ; ) {
       
// Do stuff  
   
}
?>

One less variable to toss on the heap.  NOTE that rather inconveniently, the $i goes to and hits zero only in the case where it starts out positive.  When it is zero to begin with, it will become -1.  Bug or feature?  I've used it as a feature as a quick test of whether the $arrData array was empty to begin with.  If you don't plan on using $i after the loop for anything, it makes no difference.

If you need to be doing something ascending-sequential though, then the temporary variable suggestions that others have made makes the most sense.

Finally (and important) ... if the $arrData array is somehow being dynamically modified in size due to the //Do-Stuff routine underneath, then you may have little-to-no recourse except to use the sizeof() method/function in the loop.  Or, keep up the temporary variable in the loop as you push and pop things into and off the array. 

(sigh... this is the notable failing of deeply linked internal data structures: to figure out the size of any linked list of arbitrarily composed elements, the entire array needs to be "walked" every time the sizeof() or count() method is used.  But compared to the flexibility of associative arrays, the cost is mitigated by careful use.)

GoatGuy

<< Back to user notes page

To Top