5

I have two arrays

$alpha=array('a','b','c','d','e','f');

$index=array('2','5');

I need to remove the items in the first array that has the index from the second array.

(Remove c-index is 2 and f-index is 5)

So that the returned array is

{'a','b','d','e'}

How can i do this using PHP? Thanks

Edit

Actually I need the final array as follows

[0]=>a
[1]=>b
[2]=>d
[3]=>e

Unsetting will return the array with same indexes

0 => string 'a' 
2 => string 'c' 
3 => string 'd' 
4 => string 'e' 
2
  • 1
    If you're in this for the Karma, get over yourself. Help the community, not the user. Commented Jul 26, 2012 at 17:30
  • @Matt It's nice to show appreciation when somebody solves your problem. Not required by any means, but nice. If a user doesn't care enough to do that, or doesn't know how the community works, then that user isn't adding any of value to the community. Besides, it's not like I'm telling him to accept my answer (I don't even have one) or anything. Commented Jul 26, 2012 at 18:07

5 Answers 5

3
foreach ($index as $key) {
    unset($alpha[$key]);
}

had it as array_unset() before.

Sign up to request clarification or add additional context in comments.

6 Comments

array_unset must be a new function not yet created...
Gives me an error Fatal error: Call to undefined function array_unset()
Sorry, I corrected the answer. It's unset() not array_unset()
instead of array_unset() use unset($alpha[$key])
The best code is: var_dump(array_diff_key($alpha, array_flip($index)));
|
3

Please, try this for more performance:

var_dump(array_diff_key($alpha, array_flip($index)));

Comments

2

Another method (in case $alpha or $index happen to be big and you want to keep it all on php):

function remove_keys($array, $indexes = array()){
  return array_intersect_key($array, array_diff(array_keys($array),$indexes));
}

IDEOne Example

Comments

1

Iterate through the keys in your $index array and remove the corresponding key during the iteration using unset():

<?php
$alpha=array('a','b','c','d','e','f');  
$index=array('2','5'); 

foreach ($index as $key) {     
    unset($alpha[$key]);
} 

var_dump($alpha);
?>

Output:

array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [3]=> string(1) "d" [4]=> string(1) "e" } 

Comments

0

Check this:

$array = array('a', 'b','c');
unset($array[0]);
$array = array_values($array); //reindexing

1 Comment

This will only unset the value at array index 0. It won't shift anything in the array, you'll just have array(2) { [1]=> string(1) "b" [2]=> string(1) "c" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.