简体   繁体   中英

List all keys except for one in associative array

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>";
   }    
   ?>

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;
}   

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM