Vasil Shaddix Vasil Shaddix - 16 days ago 13
PHP Question

Strange for loop syntax

I've been programming in php for about 2 years now.

I just stumbled into this for loop:

// Check the URI namespace for a context
$wsDir = basename(dirname(__FILE__));
$uriArr = explode("/", $_SERVER['REQUEST_URI']);

for (
$i = 0, $uriSize = sizeof($uriArr);
$i < $uriSize && $uriArr[$i] != $wsDir && $i++;
);

$i++;
self::$executionContext = isset($uriArr[$i]) && !empty($uriArr[$i]) && substr($uriArr[$i], 0, 1) != '?'
? strtoupper($uriArr[$i]) : 'SOAP';


and I have no idea how this is supposed to work.

Can someone explain this to me ?

Answer

It is just a normal three-part for loop without its main statement and an empty third part.

From the manual:

for (expr1; expr2; expr3)
      statement

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).

So:

for (
    # initializes two variables
    $i = 0, $uriSize = sizeof($uriArr);

    # conditional, expr2
    $i < $uriSize && $uriArr[$i] != $wsDir && $i++;

    # no expr3
);

If the expr2 evaluates to true the loop continues. Of course there is no statement or block to execute, so it just jumps to the next iterarion, meaning expr2 will be executed repeatedly until it evaluates to false at some point.

As pointed out by R. Chappell in the comments, this is probably to find a position in a string. You could rewrite this with a similar logic but in a more "descriptive" way:

$uriSize = sizeof($uriArr)

for ($i = 0; $i < $uriSize; $i++) {
    if ($uriArr[$i] == $wsDir) break;
}

# now $i will be the index of the first $wsDir occurrence in the $uriArr array