5

How can i unset a range of keys between say 70 to 80 in an array like this?

[63] => Computer Science and Informatics
[64] => Dentistry
[65] => Development Studies
[66] => Drama, Dance and Performing Arts
[67] => Earth Systems and Environmental Sciences
[68] => Economics and Econometrics
[69] => Education
[70] => Electrical and Electronic Engineering
[71] => English Language and Literature
[72] => Epidemiology and Public Health
[73] => European Studies
[74] => French
[75] => General Engineering and Mineral & Mining Engineering
[76] => Geography and Environmental Studies
[77] => Geography and Environmental Studies
[78] => German, Dutch and Scandinavian Languages
[79] => Health Services Research
[80] => History
[81] => History of Art, Architecture and Design
[82] => Iberian and Latin American Languages
[83] => Infection and Immunology
[84] => Italian
[85] => Law
[86] => Library and Information Management
[87] => Linguistics
[88] => Mechanical, Aeronautical and Manufacturing Engineering
[89] => Metallurgy and Materials
[90] => Middle Eastern and African Studies
1
  • its to remove 67 keys, so dont want to unset each individually Commented Feb 28, 2010 at 22:25

2 Answers 2

12

You can try array_slice

$return = array_slice($original, 0, 60)

then

$return = $return+array_slice($original, 70)

or

array_splice

$return = array_splice($original, 60, 10)
Sign up to request clarification or add additional context in comments.

2 Comments

This works, but it's really inefficient. You're creating 3 arrays in addition to the one you start with.
Given the fact that it is a fairly small data set, I would probably go with this solution, I don't think its efficiency is going to have any perceptible impact on performance, plus it is readable and somewhat elegant. Voted up.
11

There isn't really a shortcut to this:

for ($i = 70; $i <= 80; $i++)  
    unset($array[$i]);

3 Comments

+1 for this one too, its a simpler solution and gets the job done the same
It's kind of dissapointing, all the PHP coders who always ask if there's a function to do something bizarrely niche, when a for()/foreach() loop does it just fine.
Can you step forward through the array during the unset? Doesn't that cause an issue with changing the index of the next element to be unset as you move through? I would have thought you had to step through from 80 to 70, decrementing i.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.