2

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.

1
  • 2
    unset($myarray[array_search(min($myarray), $myarray)]); Commented Dec 6, 2013 at 7:45

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

6 Comments

the indexes are unknown as the array is dynamic
then try the second option and let me know :)
sir , the seconds options works without any problem :) , thank you
I'm glad this was of help :) feel free to upvote my answer if it was useful tu you.
Sir, why did you use reference in the parameter of the unset_min() function ?
|

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.