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 unde开发者_Go百科rstand 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 )
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.
Someone's tripped over De Morgan's laws again...
if( $key != 4 && $key != 6 ) {
Assuming you don't really need the loop, this will do the same thing:
unset($test[4], $test[6])
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 ) {
There is a native PHP function:
$values = array_diff_key ($test , array('4'=>'','6'=>''));
精彩评论