sqlchild
sqlchild

Reputation: 9064

how to remove values from an array but keep indexes intact

I have an array : $myarray = array(153=>2 , 154=>0 , 155=>10 , 156=>15 , 157=>8)

I did : sort($myarray); then , to remove the lowest ones, I did array_shift twice , but that reordered the indexes...but I need to keep the indexes unchanged.

Required output is :$myarray = array(155=>10 , 156=>15 , 157=>8)

The array is dynamic so indexes are unknown.

Upvotes: 2

Views: 1317

Answers (2)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

If you know the indexes you want to remove, you can simply do:

unset($myarray['first_index_here']);
[... unset more indexes ...]

see also the docs: http://www.php.net/manual/en/language.references.unset.php

If you want to remove the one with smallest value, as per @Leri suggestion, you can try:

unset($myarray[array_search(min($myarray), $myarray)]);

you can also make it into a function and then use it multiple times:

function unset_min(&$array) {
  unset($array[array_search(min($array), $array)]);
}

$myarray = array(153=>2 , 154=>0 , 155=>10 , 156=>15 , 157=>8);

// by hand
unset_min($myarray); // removed key 154
unset_min($myarray); // removed key 153

// or with loops
for($i = 0; $i < 2; ++$i) { // replace "2" with the actual number of entries to remove
  unset_min($myarray);
}

Upvotes: 2

Alma Do
Alma Do

Reputation: 37365

First of: your error starts at using sort() - it will reset keys. Use asort() instead. Next, use array_slice() with fourth parameter as true to preserve keys:

$myarray = array(153=>2 , 154=>0 , 155=>10 , 156=>15 , 157=>8);
asort($myarray);
$myarray = array_slice($myarray, 2, null, true);

Upvotes: 5

Related Questions