简体   繁体   中英

Find and remove specific items from numeric array

$list = array('red', 'blue', 'white', 'green', 'black', 'orange', 'brown', 'violet', 'magenta'); 

Before doing var_dump($list), how can I remove item having key [3] and item with the value "orange", and then var_dump($list) without those items?

(Have to use "if" statement - school assignment)

foreach ($list as $key => &$value)
{
    if ($value == 'orange' || $key == 3)
    {
        unset($list[$key])
    }

    echo $value . "\n";
}

What have you tried though? working through problems will help you become a better programmer.

Without loop

    $list = array('red', 'blue', 'white', 'green', 'black', 'orange', 'brown', 'violet', 'magenta'); 
    unset($list[3]);
    unset($list[array_search('orange', $list)]);
    var_dump($list);

The problem could be solved using the foreach above, or you could use the criteria that you only need to use an "if" statement.

Combining the two answers above would give a more efficient solution:

unset($list[3]);
if (($key = array_search('orange', $list)) !== false)
    unset($list[$key]);
print_r($list);

unset simply eliminates that element from the array. I will get the $key for 'orange', if it exists, then unset it, and finally print the array.

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