Reputation: 13
This should be simple, but I'm not getting the expected result. The browser either lists all the elements in the array (when I include the "!" operator) or doesn't list any elements (when I don't include the "!" operator). I'm just trying to list everything except for one element or to only list that one element. I can't get either way to work.
$features = array(
'winter' => 'Beautiful arrangements for any occasion.',
'spring' => 'It must be spring! Delicate daffodils are here.',
'summer' => "It's summer, and we're in the pink.",
'autumn' => "Summer's over, but our flowers are still a riot of colors."
);
<h1>Labeling Array Elements</h1>
<?php
foreach ($features as $feature) {
if(array_key_exists('autumn', $features)) {
continue;
}
echo "<p>$feature</p>";
}
?>
Upvotes: 1
Views: 1398
Reputation: 8288
you may also using array_filter for this approach :
$features = array(
'winter' => 'Beautiful arrangements for any occasion.',
'autumn' => "Summer's over, but our flowers are still a riot of colors.",
'spring' => 'It must be spring! Delicate daffodils are here.',
'summer' => "It's summer, and we're in the pink.",
);
print_r(array_filter($features, function ($key) {
return $key != 'autumn';
}, ARRAY_FILTER_USE_KEY));
live demo : https://3v4l.org/Ctn8O
Upvotes: 1
Reputation: 24549
When you do the continue
inside the loop simply because it exists in the array, it stops on the first iteration. That is always true.
Instead, you need to do something like this:
foreach ($features as $season => $description) {
if ($season == 'autumn') {
continue;
}
echo $description;
}
Upvotes: 2