Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Shane McC
3,005 PointsPHP Array Looping Question
Hi Everyone,
I want to display certain information based upon what a specific variable is stating via an array. I'm have trouble doing so. What I'm trying to do in my below syntax is this, based on the states of Colorado and Delaware I want to display certain text but all other states I want to display other text. The below syntax is looping through all of the states which isn't what I want. I want this, if a state is "Colorado" I want to echo certain information and stop, not continue to loop. What am I doing wrong? Thanks
$cars = array ("Colorado", "Delaware","Alabama");
foreach($cars as $key){
echo "$key".'<br>';
if($state == $key){
echo "Write something about the state here".'<br>';
} else {
echo "Write something else here".'<br>';
}
}
1 Answer
David Andrews
17,403 PointsHey Shane,
To exit a loop in PHP use the break keyword.
Example
$cars = array ("Colorado", "Delaware","Alabama");
foreach ($cars as $key)
{
// Code here
if ($state == $key)
{
// More code;
break; <---- this will exit the foreach loop
}
}
More details here
Shane McC
3,005 PointsShane McC
3,005 PointsAppreciate that, works great