PHP: (Ab)using the For-Loop

22 07 2017

Flickr:  by mald

This blogpost draws inspiration from a similar one exploring ways to use or abuse loops in the C Programming Language; see here.  Whatever your familiarity with for-loops in PHP, you may be surprised that one may code as follows:

<?php 
function loop_prologue() {
    printf("starting loop\n");
}
function loop_epilogue() {
    printf("terminating loop\n");
}
function loop_iter() {
    printf("iteration\n");
}
$x = 3;
for ( loop_prologue();
      ($x-- >= 1) || (loop_epilogue());
      loop_iter() );

See demo.

The code has a for-loop without a body.  Nonetheless, it executes and displays output, too.  Furthermore, the initialization section contains nothing of the sort in its code and the increment section increments nothing at all.  Instead, each of these sections evaluates as true, so the loop is viable.

The code may contain a loop-body, as follows:

<?php 
function loop_prologue() { 
    printf("starting loop\n");
}
function loop_epilogue() {
    printf("terminating loop\n");
}
function loop_iter() {
    printf("iteration\n");
}
$x = 3; 
for ( loop_prologue();
      ($x-- >= 1) || (loop_epilogue());
      loop_iter() )
{
    echo "$x\n";
}

See demo.

You may also write code like the following:

<?php
function loop_epilogue():void {
      echo "terminating loop\n";
      return;
}
function loop_iter() {
     echo "iteration\n";
}
$x = 1;
for ( FALSE;
      ( ( $x-- >= 1 ) || ( loop_epilogue() ) );
      loop_iter()
     );

With this last example, it is important that the traditional increment section not return true, otherwise an endless loop results. Returning void, false or null will all stop the loop.

This work is licensed under a Creative Commons License

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: