• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / PHP for loops with multiple statements in each expression

PHP for loops with multiple statements in each expression

PHP for loops work in the same way as other programming languages and have a useful feature where each expression between the semi-colons can have multiple statements to be executed when separated by a comma. I found this useful myself when I need to have both a zero based and 1 based index in a loop.

PHP for loops

As in other programming languages, PHP for loops work like this:

for( expression1; expression2; expression3 ) {     
    code to run in the loop
}

where expression1 if executed once at the start of the loop; expression2 determines whether the loop should continue on each iteration; and expression3 is executed at the end of each loop.

Executing multiple statements in each expression

What many people do not realise is that multiple statements can be executed in expression1 and expression3 by separating them with commas. For example in psuedo code:

for( expression1a, expression1b; expression2; expression3a, expression3b ) {
    code to run in the loop
}

In my case, I needed to have both a zero based index and a 1 based index inside the loop. A more obvious way to do this with single expressions would be like so:

for( $i = 0; $i < $max; $i++ ) {
     $j = $i + 1;
     // code to run in the loop
}

The alternative way by putting all the assignments into the for( ) part is like this:

for( $i = 0, $j = 1; $i < $max; $i++, $j++ ) {
    // code to run in the loop
}

See also my other post about PHP for loops and counting arrays.

Check Out These Related posts:

  1. Bash For Loop
  2. Find the index of the element that was clicked with jQuery
  3. How to use an associative array with PHP’s str_replace function
  4. Assigning values to associative arrays in Javascript

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap