thomashw Posted March 21, 2008 Share Posted March 21, 2008 Is it possible to unset an array so the key that is being unset is deleted and all others move back one? For instance: If you had an array which contained planes[1], planes[2], planes[3], etc. And you deleted planes[2], then planes[3] would become planes[2]. Making the array to be just planes[1], planes[2], etc. I'm thinking it's possible because I know it's possible in C++. Thanks! Quote Link to comment Share on other sites More sharing options...
Caesar Posted March 21, 2008 Share Posted March 21, 2008 <?php $planes = array('one', 'two', 'three'); unset($planes[1]); ?> That results in... Array ( [0] => one [1] => three ) Quote Link to comment Share on other sites More sharing options...
Caesar Posted March 21, 2008 Share Posted March 21, 2008 I'll add that you can pretty much do what you want with the values in an array. So yes, you can do what you want. If you defined the keys in the array, you can redefine them. Quote Link to comment Share on other sites More sharing options...
thomashw Posted March 21, 2008 Author Share Posted March 21, 2008 I have the following code: unset ($_SESSION['name'][$number]); $number is whichever array is being unset. So if number = 1, then 0 and 2 still exist but 1 is erased (and 2 doesn't come down to 1.) Quote Link to comment Share on other sites More sharing options...
Jeremysr Posted March 21, 2008 Share Posted March 21, 2008 This might work: function array_remove($array, $removed_key) { $new_array = array(); foreach ($array as $key => $value) { if ($key != $removed_key) { array_push($new_array, $value); } } return $new_array; } $_SESSION['name'] = array_remove($_SESSION['name'], $number); Quote Link to comment Share on other sites More sharing options...
thomashw Posted March 21, 2008 Author Share Posted March 21, 2008 Thanks for the function. I'm just bewildered there isn't a preset function that will do this. Unless I'm using "unset" incorrectly. Quote Link to comment Share on other sites More sharing options...
thomashw Posted March 22, 2008 Author Share Posted March 22, 2008 I found the function array_values(); does the job - for anyone who sees this in the future! The function goes through the array and indexes everything numerically. So after using the unset(); function, the array_values(); function can be used to completely remove the key from the array and put everything back in order. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.