-1

I want to delete multiple items array without disrupt order the key. So what is the best way to do that problem? because i tried use splice but the key is skipped for deleted element

the example :

$del_item = array('orange', blueberry);
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
print_r($array);
//[0]=>"apple", [1]=>"orange", [2]=>"strawberry", [3]=>"blueberry", [4]=>"kiwi"

$deleted= array('apple', 'strawberry', 'kiwi');
print_r($deleted);
//[0]=>"apple", [1]=>"strawberry", [2]=>"kiwi"
Ray Coder
  • 1,022
  • 3
  • 15
  • 30
  • *because i tried use splice but the key is skipped for deleted element* - you want the keys remain there with blank values? – Sougata Bose Oct 31 '19 at 08:53
  • You have not deleted anything you create two arrays and obviously they look different. If you unset (delete) an item then you will get the result you are looking for – Andreas Oct 31 '19 at 08:55
  • @SougataBose i want the order key remain 0 1 2 3 4 5 ... – Ray Coder Oct 31 '19 at 09:07

2 Answers2

2

You can use array_diff with array_values as

$deleted = array_values(array_diff($array, $del_item));

The array_diff will delete the item you want and the array_values will reindex them

dWinder
  • 11,597
  • 3
  • 24
  • 39
1

You can iterate the array, Demo

$del_item = array('orange', 'blueberry');
$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$del_item = array_flip($del_item);
$result = [];
foreach($array as $key => $value){
    if(!isset($del_item[$value])){
        $result[$key] = $value;
    }
}
print_r($result);
LF00
  • 27,015
  • 29
  • 156
  • 295