php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #24626 foreach stops with boolen expresion in loop
Submitted: 2003-07-12 17:45 UTC Modified: 2003-07-12 18:23 UTC
From: eric at austarmetro dot com dot au Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 4.3.3RC1 OS: Win XP
Private report: No CVE-ID: None
 [2003-07-12 17:45 UTC] eric at austarmetro dot com dot au
Description:
------------
The foreach loop exits early and sets the $status variable to "".
The problem is fixed by changing 
$status = $status && status( $b );
to
$status &= status( $b );

Hope this is bogus :)
I have tried this on WinXP PHP4.3.3RC1 and FREEBSD PHP4.3.1 both give the same result.

Eric


Reproduce code:
---------------
<?
function status( $c ) {
   echo $c;
   if( $c == 'two' )
      return 0;
   return 1;
}

$a = array( 'one ','two ','three ','four ' );
$status = 1;
foreach( $a as $b )
{
 $status = $status &&  status( $b );
}
echo " foreach stopped. Status = ".$status;
if( isset( $status ) )
 echo " set ";
else
 echo "unset";
?>

Expected result:
----------------
onetwothreefour foreach stopped. Status = 0 set

Actual result:
--------------
onetwo foreach stopped. Status = set

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-07-12 18:23 UTC] elmicha@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions. 

Thank you for your interest in PHP.

"&&" is a boolean operator, "&" works bitwise (on integers, not on strings). "&=" also works bitwise.

And $c == 'two' does never happen in the script you posted. If you remove the spaces from your $a values, $status('two') will return 0, which makes $status 0. After that, the status() function is never called again, because $status already is 0, which is equivalent to false ("short-circuit evaluation"). Stick some echos in the loop and you'll see that it works just fine.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Jul 15 17:01:33 2025 UTC