Home » Php » php – Remove common indexes of array

php – Remove common indexes of array

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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
)

Answer:

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);
$mainArray=array('1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f');

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

print_r($t);

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

Answer:

try unset function. This must work perfect.

unset($mainArray[1]);