Removing key => value pairs from an array, but its not removing them

筅森魡賤 提交于 2019-12-10 12:45:25

问题


I am trying to remove two key value pairs from an array, I am using the code below to segregate out the keys I don't want. I don't understand why it is not equating properly. if I remove the OR (|| $key != 6) it will work properly but I was hoping to have one if statement. Can anyone explain what I'm doing wrong? Thanks.

$test = array( '1' => '21', '2' => '22', '3' => '23', '4' => '24', '5' => '25', '6' => '26'  );

foreach( $test as $key => $value ) {
    if( $key != 4 || $key != 6 ) {
        $values[$key] = $value;
        echo '<br />';
        print_r( $values );
    }
}

// Output
Array ( [1] => 21 [2] => 22 [3] => 23 [4] => 24 [5] => 25 [6] => 26 ) 

回答1:


This is the best way to do that:

$values = $test;
unset($values[4], $values[6]);

Assuming that you need a new array $values. Otherwise remove them directly from $tests.

Reference here: http://php.net/unset


The following is just for your own education in boolean logic, it's not the way you should do it.

You need to change || to &&. You don't want either in the result. With logical OR, all of them will get through because 4 != 6 and 6 != 4. If it hits 4, it will run like this:

Are you not equal to 4? Oh, you are equal to 4? Well, the best I can do is let you though if you're not equal to 6.

If you change it to &&, it will run something like this:

Are you a number besides 4 or 6? No? Sorry pal.




回答2:


Someone's tripped over De Morgan's laws again...

if( $key != 4 && $key != 6 ) {



回答3:


Assuming you don't really need the loop, this will do the same thing:

unset($test[4], $test[6])



回答4:


Your condition is wrong. if you dont want to take key 4 and 6 then your condition should be like this

foreach( $test as $key => $value ) {
   if( $key != 4 && $key != 6 ) {



回答5:


There is a native PHP function:

$values = array_diff_key ($test , array('4'=>'','6'=>''));


来源:https://stackoverflow.com/questions/7035332/removing-key-value-pairs-from-an-array-but-its-not-removing-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!