PHP - Remove Item From Array & Shift Keys

In PHP there are times when you want to take an item out of your array and maintain the right key numbering. Example of what I'm talking about:
$food = array('apple','orange','banana','grape');
print_r($food);

Output:
Array
(
[0] => apple
[1] => orange
[2] => banana
[3] => grape
)

Now lets say I want to eat (remove) the banana. A typical and logical way to do this would be to unset($food[2]); This would leave us with the following array:

Array
(
[0] => apple
[1] => orange
[3] => grape
)

This becomes a problem if you want to iterate through your fruits like this:
for ($i = 0; $i

A simple fix if it's your code is to change it to: foreach ($fruits as $fruit)

But what about other people's code? Specifically for me it was Smarty's {section} tag that was bothering me. I know smarty's code is freely available so I could go in and fix it but that was more hassle than my solution. Here's how to remove an item and have the keys re-order themselves:

array_splice($fruits, $key, 1);

In our case, $key = 2 for banana. So it would be: array_splice($fruits, 2, 1);

Here's the result:
Array
(
[0] => apple
[1] => orange
[2] => grape
)

Now Smarty is happy, you're happy, and hopefully you found this little hack before you wrote some longer code to renumber your keys.

Comments

In the future when you update Smarty, hopefully you'll remember that you did this. Otherwise it might make for some fun debugging.

The whole point of doing it this way is so that you don't have to modify Smarty.

Thank you, that was JUST the code I needed! I did indeed find it before writing longer mucky code.