[nycphp-talk] Removing one element from an array
David Krings
ramons at gmx.net
Mon Jul 9 22:22:26 EDT 2007
Cliff Hirsch wrote:
> Look at array_slice
>
Based on the vote tally array_slice won, but I don't get this command. I
just went for broke and tried my unset suspicion and indeed it works.
This is the scenario: I have abunch of record IDs in an array, which I
stuffed into the $_SESSION variable. The IDs belong to pictures and I
just deleted one picture, which means that I need to remove the
non-existent ID from the array.
This is the code:
// Remove current element from display array
$display = $_SESSION['sessiondisplay'];
unset($display[$_SESSION['sessionviewpointer']]);
// Rekey display array
$display = array_values($display);
// register new array with $_SESSION
$_SESSION['sessiondisplay'] = $display;
The unset on a specific array key unsets only that value. The array key
is gone and thus the value is no longer in the array. Rekeying using
array_values patches the hole and gets me a consecutive, numerically
keyed array.
I also store the current pointer in $_SESSION and as it turns out I
don't even have to do anything with the pointer as it automatically
points at the next array element.
Nevertheless, I am intrigued by array_slice, but I guess I postpone
understanding that until tomorrow.
Thanks for the pointers.
David
More information about the talk
mailing list