views:

108

answers:

4

I have 1 array that I want to re-index. I have found that both array_values and array_merge functions can do the job (and I don't need 2 arrays for the array_merge function to work).

Which is faster for a very large array? I would benchmark this, but I don't know how and don't have the large array yet.

Before re-index:

Array
(
    [0] => AB
    [4] => EA
    [6] => FA
    [9] => DA
    [10] => AF
)

After re-index:

Array
(
    [0] => AB
    [1] => EA
    [2] => FA
    [3] => DA
    [4] => AF
)
+2  A: 

array_values is meant to do exactly what you want it to do. array_merge is meant to do something else and you got a workaround to make it work on your case. (although you might have problems if a non-numerical value is forgotten in the indexes).

I don't know if there are significant performance differences but for sure code written with array_values is easier to read. And I don't think that a function that is meant to do something is slower than one meant to do something else.

Hope this helps.

vladv
+1  A: 

I haven't done the benchmarks either -- and if you need to be sure, you should do them.

That said, I would suspect that if one is preferable to the other, array_values() is going to be the way to go.

After all, what you want to do is exactly what array_values() was designed for.

timdev
+1  A: 

It's important to note that array_merge() will only reset the array keys if there are no string keys in the array.

too much php
A: 

I got the bench mark, array_value is 3x faster (sorry to answer my own question, the comment section does not retain the format)

for and array with 8043 elements

array values took 0.003291130065918 seconds.

array merge took 0.0096800327301025 seconds.

$shuf is the un-indexed array

Below is the code for running the benchmark (copied it off the web)

    $sha1_start = microtime(true); 
    $arraymerge = array_merge ($shuf); 
    $shal_elapsed = microtime(true) - $sha1_start;


    $start = microtime(true); 
    $arrayvalue = array_values ($shuf); 
    $elapsed = microtime(true) - $start;

echo "<br>array values took $elapsed seconds."; 
echo "<br>array merge took $shal_elapsed seconds.";
Jamex