1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Recently I’ve learned one nice trick with for loop. When you use it, you should know he number of itereations. Most people do it like this:

  1.  
  2. $a = array(1,2,3,4,5);
  3. $s = sizeof($a);//you may use count(), but sizeof if 5% faster :)
  4. for ($i = 0; $i < $s; $i++)
  5. {
  6. //do something clever here
  7. echo $a[$i].
  8. ;
  9. }
  10.  

But this requires counting number of elements before using a loop. However, writing like this:

  1.  
  2. $a = array(1,2,3,4,5);
  3. for ($i = 0; $i < sizeof($a); $i++)
  4. {
  5. //do something clever here
  6. echo $a[$i].
  7. ;
  8. }
  9.  

is really awful – you count number of elements on each iteration, never use this!
And nice trick I was talking about is using the “,” (comma) operator:

  1.  
  2. $a = array(1,2,3,4,5);
  3. for ($i = 0, $s = sizeof($a); $i < $s; $i++)
  4. {
  5. //do something clever here
  6. echo $a[$i].
  7. ;
  8. }
  9.  

See the initial condition: $i = 0, $s = sizeof($a) – we set $i to 0, as usual, and then – $s – to number of elements in array. Just several commands in one line.
Another usage of comma operator is:

  1.  
  2. for ($i = 0, $j = 0; $i < 10; $i++, $j+=5)
  3. {
  4. //each iteration we increment $i by 1 and $j by 5. Maybe you find some useful example of this :)
  5. }
  6.  

The above tricks apply to almost any language, that has similar for() syntax – C, C++, PHP, JS (not sure about Java, but it should be there also)

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Share this post with a friend Share this post with a friend

7 Comments

  1. creocoder says:

    How about this:

    $array = array(1,2,3,4,5);
    foreach ($array as $a) {
    //do something clever here
    echo $a.”;
    }

  2. Konstantin Mirin says:

    Sure, it’s OK, but see this: http://www.php.lt/benchmark/phpbench.php
    Anyway, it’s not recommendation to use for instead of foreach, just a little trick, that saves a line of code :)

  3. creocoder says:

    Konstantin, I don’t understand you. Your comments are in contradiction with your ideology. On the one hand, “I don’t like to work with Drupal or jQuery. I enjoy ExtJS, for example. And I wanted the same nicely designed PHP framework.” – you write this in your post about Yii. When you perform some useful action in the body of the “for” loop, you get bad code design. And Performance is not a key here. It’s better to write:
    foreach (array(1,2,3,4,5) as $a) { echo $a; }

    Something like http://kpumuk.info/php/crazy-php-world/

  4. Konstantin Mirin says:

    I can’t understand how this trick refers to the application design and MVC pattern. Sure, I use both for and foreach loops – whichever is better for some specific case. And it is not related to controller or model in any way :)

  5. jz says:

    IMHO, “foreach” is universal way to iterate over arrays. For “for”, if you change some code from “array($a, $b)” to “array(‘a’=>$a, ‘b’=>$b)” you must rewrite other code (MVC example: rewrite code in controller => rewrite code in view). However, this is rare case.

  6. Konstantin Mirin says:

    Universal – yes. But is it really a good idea to use foreach when sorting? :) I just showed how to get rid of unnecessary extra line using the comma operator.

  7. jz says:

    I use described practice in C++ and for huge arrays in PHP. And yes, this is only one trick with “for” loop, no more.

    P.S. Забавно, как такая простая и человеческая заметка о маленькой хитрости, не претендующая на отчёт о тестировании и описание какой-то парадигмы программирования, заполучила столько пространных комментариев, доходящих разговоров о MVC :)

    —————–
    Translation by Konstantin:
    P. S. It’s funny to see, how this simple and useful note about the little trick, that doesn’t claim to be some testing report or description of some development paradigm, got so many large comments, that lead to MVC discussion :)

Leave a Reply