How to efficiently remove an element from an array in PHP
06 Jul 2017Recently I was looking for an efficient way to remove an element from a given offset in a given PHP array. And my first thought was to use the array_splice method, but I began to wonder if it is the best option to do so. I searched through the net and I’ve stumbled upon a Steven Vachon’s webpage, where the author compared this option with another one: a combination of unset and array_values methods. His benchmark proved that it was the latter that was over 10% faster. But I couldn’t believe that a combination of two methods will be faster than a single one. So I’ve made my own benchmark.
The code for my benchmark:
The results:
- Splice: 2.041 seconds. Array size: 10000
- Unset with array_values: 25.069 seconds. Array size: 10000
Splice is a clear winner.