Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove common indexes of array

Tags:

arrays

php

I have some indexes that I need to remove from main array. For example:

$removeIndex=array(1,3,6);
$mainArray=array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f');

I want end result like:

 $mainArray=array('2'=>'b','4'=>'d','5'=>'e');

I know we have array_slice function in PHP, which can be run in loop, but I have very huge data and I want to avoid looping here.

like image 272
Jacklish Avatar asked Jun 17 '13 07:06

Jacklish


1 Answers

Perhaps try array_diff_key:

$removeIndex=array(1,3,6);
$mainArray=array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f');
$removeIndex = array_flip($removeIndex);//flip turns values into keys
echo '<pre>';
//compute diff between arr1 and arr2, based on key
//returns all elements of arr 1 that are not present in arr2
print_r(array_diff_key($mainArray, $removeIndex));
echo '</pre>';

When I tried this, it returned:

Array
(
    [2] => b
    [4] => d
    [5] => e
)
like image 149
Elias Van Ootegem Avatar answered Oct 29 '22 23:10

Elias Van Ootegem