Search code examples
phparray-unset

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


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 ) 

Solution

  • 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.