arrays with holes

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
still! a php newbie.  This is kind of a touch base question.  I think
I have it...

I have an indexed array in which I progressively remove elements with


This leave "holes", which I'm ok with.

To now find the 5th element in this shot-up array I use

    $my_array_piece =  array_splice($my_array, 5, 1);

Is that how you "do" it?

Unfortunately, the "indexes" have meaning.  I don't want to repack.

Re: arrays with holes

Quoted text here. Click to load it

Oops... I mean array_splice($my_array, 4, 1) for the 5th element

Re: arrays with holes

El 20/01/2012 21:44, cate escribió/wrote:
Quoted text here. Click to load it

If array keys are meaningful but unknown, I can't figure out many other
ways to find for the nth element than array_splice(). But you need to
read the manual page carefully: your code, as is, will get rid of the
key. Check the forth parameter.

-- - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:
-- Mi web de humor satinado:

Re: arrays with holes

.oO(Álvaro G. Vicario)

Quoted text here. Click to load it

I think you could also use array_keys() and then get the nth key.
Something like this (untested and without any error checking):

function getElement(array $array, $index) {
  $keys = array_keys($array);
  return $array[$keys[$index]];

Wrap the whole thing into your own array class and you could even do

$foo = $array['foo'];
$bar = $array[5];

where the first statement would directly return the element with the key
'foo' and the second one the element at the 6th position, regardless of
the keys (using the function from above).

Just a quick idea.



Site Timeline