Home » Php » php – Remove common indexes of array

php – Remove common indexes of array

Posted by: admin July 12, 2020 Leave a comment


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


I want end result like:


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.

How to&Answers:

Perhaps try array_diff_key:

$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:

    [2] => b
    [4] => d
    [5] => e


you can use array_diff_key, note that in removeIndex array you need to make the values as keys

$removeIndex=array('1' => 0,'3' => 0,'6' => 0);

$t = array_diff_key($mainArray, $removeIndex);


As @Elias pointed out you can use array_flip to change the values to keys in your removeIndex array.


try unset function. This must work perfect.