Page 1 of 1

need to trim one slice from a multidimensional array

Posted: Fri Jun 27, 2008 12:41 am
by phertzog
Hi there,

I have what I think is probably a pretty simple question. I have a multi-dimensional array stored in a session, and I need to be able to delete the values for one particular slot in that array.

For example, if my array looks like:

Code: Select all

$_SESSION['myarray'] = array(
                            array(x=>'123', y=>'456', z=>'789'),
                            array(x=>'abc', y=>'def', z=>'ghi'),
                            array(x=>'red', y=>'green', z=>'blue'),
                            array(x=>'etc', y=>'etc', z=>'etc')
                        );
then I might need to delete the values in, say, the second slot:

Code: Select all

array(x=>'abc', y=>'def', z=>'ghi')
What I was sorta thinking was that if I could bump that sub-array to the beginning of the main $_SESSION['myarray'] array, then I could use array_shift() to remove it and its values. I just haven't been able to find a php function that would allow me to specify a particular slot in the array and move it to the top.

I hope this makes sense.

Any input will be VERY appreciated!

Re: need to trim one slice from a multidimensional array

Posted: Fri Jun 27, 2008 1:20 am
by John Cartwright
unset, and using your particular example, you would do

Code: Select all

unset($_SESSION['myarray'][1]);

Re: need to trim one slice from a multidimensional array

Posted: Fri Jun 27, 2008 2:10 pm
by phertzog
Thanks Jcart!

I had thought about just using unset() as you described. The problem I ran into was that instead of the array indices being number sequentially [0,1,2,3,etc..] they would be numbered like this [0,2,3,etc] once one of those middle indices was removed. So that's why I was wondering whether one of the php functions that re-sorts the indices would have been handy.

Is there a simple way to re-index the array so that the index numbers are sequential again after using unset() to remove an index somewhere in the middle?

Thanks again!