need to trim one slice from a multidimensional array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phertzog
Forum Newbie
Posts: 2
Joined: Thu Jun 26, 2008 10:58 pm

need to trim one slice from a multidimensional array

Post 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!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: need to trim one slice from a multidimensional array

Post by John Cartwright »

unset, and using your particular example, you would do

Code: Select all

unset($_SESSION['myarray'][1]);
phertzog
Forum Newbie
Posts: 2
Joined: Thu Jun 26, 2008 10:58 pm

Re: need to trim one slice from a multidimensional array

Post 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!
Post Reply