Consider the following code:
<?php
function important_function( $i )
{
printf ("<p>Called for the %sth time.</p>\n", $i);
return ($i < 3);
}
function loop_with_and( )
{
$ret = true;
for( $i = 0; $i < 10; $i ++ )
{
$ret = $ret && important_function( $i );
}
return $ret;
}
function loop_without_and( )
{
$ret = true;
for( $i = 0; $i < 10; $i ++ )
{
if( ! important_function( $i ) )
{
$ret = false;
}
}
return $ret;
}
?>
<div>
<p><b>Call with And</b></p>
<?php loop_with_and( ) ?>
</div>
<div>
<p><b>Call without And</b></p>
<?php loop_without_and( ) ?>
</div>
Can anyone give me a good reason why the output is:
<div>
<p><b>Call with And</b></p>
<p>Called for the 0th time.</p>
<p>Called for the 1th time.</p>
<p>Called for the 2th time.</p>
<p>Called for the 3th time.</p>
</div>
<div>
<p><b>Call without And</b></p>
<p>Called for the 0th time.</p>
<p>Called for the 1th time.</p>
<p>Called for the 2th time.</p>
<p>Called for the 3th time.</p>
<p>Called for the 4th time.</p>
<p>Called for the 5th time.</p>
<p>Called for the 6th time.</p>
<p>Called for the 7th time.</p>
<p>Called for the 8th time.</p>
<p>Called for the 9th time.</p>
</div>
To me, that makes no sense; I didn't instruct the loop to finish on the first encounter of a 'false'; if that's what I'd wanted; I'd have put in a conditional break. All I can assume is that this is some kind of bug (where the loop continuation becomes dependant on the validity/return from an inner statement), or that this might actually be some kind of deliberate loop optimization attempt (which I'd consider to be thoroughly stupid; given that I'm collecting a single validity result from many unrelated , but essential, validation functions )...
Either way; can anyone test the same code on PHP5 for me? My hosting plan uses PHP 4.4.6.