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
Anonymous (not verified)
Sat, 10/06/2007 - 10:34
Permalink
In the future
In the future when you update Smarty, hopefully you'll remember that you did this. Otherwise it might make for some fun debugging.
adam
Tue, 01/15/2008 - 09:27
Permalink
Read the tip a little closer
The whole point of doing it this way is so that you don't have to modify Smarty.
Anonymous (not verified)
Wed, 12/01/2010 - 15:48
Permalink
Perfect!
Thank you, that was JUST the code I needed! I did indeed find it before writing longer mucky code.