Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Break Out Of Foreach Loop

loop

  • Please log in to reply
3 replies to this topic

#1 JakeWelton

JakeWelton

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 152 posts
  • Programming Language:Java, C++, C#, PHP, JavaScript, PL/SQL
  • Learning:Objective-C, Python, Perl, Ruby, Visual Basic .NET, Haskell

Posted 21 July 2012 - 03:23 AM

Hello all

I have the follow code:

foreach ($variable as $key => $val)
{
if ($val == "0"
{
echo "equals 0";
break;
} else {
echo "does not equal 0";
}
}

But for some reason the break is not breaking out of the loop. (the loop is working perfectly btw). Does anyone know why?

Thanks,
Jake
  • 0

sig.jpg

"Before you judge someone, walk a mile in their shoes; after that, who cares?! Their a mile away and you've got their shoes!"


#2 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 21 July 2012 - 09:30 AM

Hey Jake,
it is just a typo, here the corrected version

foreach ($variable as $key => $val)
{
     if ($val == "0" )
     {
         echo "equals 0";
         break;
     } 
     else 
     {
        echo "does not equal 0";
     }
}

what a mess the lack of one parenthesis made !
  • 0

#3 JakeWelton

JakeWelton

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 152 posts
  • Programming Language:Java, C++, C#, PHP, JavaScript, PL/SQL
  • Learning:Objective-C, Python, Perl, Ruby, Visual Basic .NET, Haskell

Posted 21 July 2012 - 12:12 PM

Thanks for that! cant believe it was that simple!!!!

Many thanks BlackRabbit!
  • 0

sig.jpg

"Before you judge someone, walk a mile in their shoes; after that, who cares?! Their a mile away and you've got their shoes!"


#4 Orjan

Orjan

    CC Mentor

  • Moderator
  • 2918 posts
  • Location:Karlstad, Sweden
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Pascal
  • Learning:Java, C#

Posted 23 July 2012 - 12:54 AM

I don't understand why you need to do a brake there, as the rest of the if don't execute. If you want to check if there is an zero in the array, it's better to use in_array(). break is something you should be very restrictive with, usually only use when you write switch-case statements or in very specific situations, this is not one of them in my opinion.
  • 0

I'm a System developer at XLENT Consultant Group mainly working with SugarCRM.
Please DO NOT send mail or PM to me with programming questions, post them in the appropriate forum instead, where I and others can answer you.






Also tagged with one or more of these keywords: loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download