Reputation: 92
Remove those array indexes whose value is 1
array (1=>1,2=>2,3=>1,4=>1,5=>3,6=>1);
result array as
array(2=>2,5=>3);
is there is a direct function in php? like
unset(key($a,1));
Upvotes: 0
Views: 79
Reputation: 3743
One liner, using array_diff
as
$your_array = array_diff ( $your_array, [1] );
Upvotes: 2
Reputation: 550
You can also use the array_flip
and can use the below code:
<?php
$arr = array(1=>1,2=>2,3=>1,4=>1,5=>3,6=>1);
$arr1 = array_flip($arr);
unset($arr1[1]);
$arr = array_flip($arr1);
print_r($arr);
?>
Upvotes: 0
Reputation: 31739
Loop through it, check and unset -
foreach($array as $k => $v) {
if($v == 1) {
unset($array[$k]);
}
}
Or use array_filter()
$newArr = array_filter($array, function($v) {
return ($v != 1);
});
Or you can use array_flip()
for some trick -
$temp = array_flip($array);
unset($temp[1]);
$array = array_flip($temp);
Upvotes: 0
Reputation: 866
Using array_search() and unset, try the following:
while(($key = array_search(1, $array)) !== false) {
unset($array[$key]);
}
Upvotes: 0
Reputation: 212412
look to use array_filter()
$myArray = array (1=>1,2=>2,3=>1,4=>1,5=>3,6=>1);
$myArray = array_filter(
$myArray,
function($value) {
return $value !== 1;
}
);
Upvotes: 2