10

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 ) 
Jonah
  • 9,991
  • 5
  • 45
  • 79
Drewdin
  • 1,732
  • 5
  • 23
  • 35

5 Answers5

19

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.

Jonah
  • 9,991
  • 5
  • 45
  • 79
  • 1
    Thanks! I kept thinking that if its not 4 or 6 and got tripped up. I appreciate it! – Drewdin Aug 12 '11 at 11:11
  • 1
    I cant tell you how many times i have to refer back to your answer, you would think i would know by now! +1 – Drewdin Aug 16 '13 at 18:09
7

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

if( $key != 4 && $key != 6 ) {
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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

unset($test[4], $test[6])
deceze
  • 510,633
  • 85
  • 743
  • 889
2

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 ) {
Rukmi Patel
  • 2,619
  • 9
  • 29
  • 41
1

There is a native PHP function:

$values = array_diff_key ($test , array('4'=>'','6'=>''));
Fox
  • 397
  • 3
  • 3
  • Great answer. I think this is the best way to remove specific keys from an array, its simple and does not require a loop. –  Jan 23 '17 at 15:59