81

My array looks like this:

array(
  0 => 'val',
  2 => 'val',
  3 => 'val',
  5 => 'val',
  7 => 'val'
);

How can I reset the keys so it will go like 0, 1, 2, 3, 4?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
stergosz
  • 5,754
  • 13
  • 62
  • 133
  • Use a foreach loop and missing index is not an issue. I use a for loop on an array and the missing index cause a problem. – Kent Tran Jul 29 '19 at 03:07

7 Answers7

179

Use array_values:

$reindexed_array = array_values($old_array);
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • array values, though valid, is not what I'd recommend. Internally, it calls the array constructor, and returns a new array. using sort is therefore (marginally) faster, and shorter to write, too – Elias Van Ootegem Jun 27 '12 at 11:12
  • i dont need to use another array.. i simply array_values() the current one – stergosz Jun 27 '12 at 11:13
  • 1
    Elias, a simple benchmark will show you that sort is never faster. It's very slow for large arrays and the memory difference is minimal for small ones. I see no reason to use sort (which also have possibly unwanted side-effects). – Emil Vikström Jun 27 '12 at 11:25
  • We all need to buy new phones often, because programmers don't care about saving memory. Why is this answer so more voted than @Rawkode's, below? – Rodrigo Oct 31 '18 at 20:44
  • 3
    @Rodrigo Because for most PHP developers CPU cores are more expensive than memory (we have gigabytes of unused RAM on all our FPM servers). And most of us do web development where response time is important. My answer is faster and uses less CPU. My answer is also more elegant because it answers the original question with no other side effects. If you don't agree with this then fine, but your rant about phones seems very unfair because I am one of those who do care about performance. I'm only saying that creating a new array in O(n) time is MORE performant than sorting it in O(n log n) time. – Emil Vikström Nov 01 '18 at 13:25
  • Thank you for taking the time to explain it. Can I edit your question to add this information, which I think is really important? – Rodrigo Nov 01 '18 at 17:07
21
array_splice($old_array, 0, 0);

It will not sort array and will not create a second array

alekveritov
  • 311
  • 2
  • 3
10

By using sort($array);

See PHP documentation here.

I'd recommend sort over array_values as it will not create a second array. With the following code you now have two arrays occupying space: $reindexed_array and $old_array. Unnecessary.

$reindexed_array = array_values($old_array);

Rawkode
  • 21,990
  • 5
  • 38
  • 45
  • How is my answer wrong? sort will rekey and sort the array, as he has asked. – Rawkode Jun 27 '12 at 11:12
  • @Rawkode why does array_values create another array if i do array_values() the current array? it seems to work that way as well – stergosz Jun 27 '12 at 11:14
  • 1
    but i dont need to use a new array for array_values since i can do $array = array_values($array) – stergosz Jun 27 '12 at 11:19
  • 1
    `sort` is *much* slower than array_values. The time complexity of `array_values` is O(n) while `sort` is O(n log n) in the best case. A simple benchmark will show you that array_values is faster than sort in all cases, especially for larger arrays (a million entries took over a second to sort on my computer, while array_values was ten times faster). Also, what if fxuser don't want to sort the values? – Emil Vikström Jun 27 '12 at 11:22
  • @fxuser Even using $a = array_values($a) you are still creating a second array behind the scenes and this will boost your memory usage. – Rawkode Jun 27 '12 at 11:31
  • @EmilVikström If he doesn't want to sort the values, then I'd suggest array_values as you have done. However, he only spoke about reindexing the keys, for which both of our ways are valid. – Rawkode Jun 27 '12 at 11:32
  • 3
    Yes, `sort` may be valid but it is way slower, especially for large arrays (those where memory matters). – Emil Vikström Jun 27 '12 at 11:39
  • 2
    This answer will be wrong anytime the values are not already in ascending order. It should not have 11 upvotes -- it is only correct because of the scenario posted in the question. – mickmackusa Jul 18 '19 at 08:47
  • with tests I found that sort will change the order of elements also. so array_values still the best choice. – Mimouni Jan 04 '22 at 15:30
4

From PHP7.4, you can reindex without a function call by unpacking the values into an array with the splat operator. Consider this a "repack".

Code: (Demo)

$array = array(
  0 => 'val',
  2 => 'val',
  3 => 'val',
  5 => 'val',
  7 => 'val'
);

$array = [...$array];

var_export($array);

Output:

array (
  0 => 'val',
  1 => 'val',
  2 => 'val',
  3 => 'val',
  4 => 'val',
)

Note: this technique will NOT work on associative keys (the splat operator chokes on these). Non-numeric demo

The breakage is reported as an inability to unpack string keys, but it would be more accurate to say that the keys must all be numeric. Integer as string demo and Float demo

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
1
array_splice($jam_array, 0, count($jam_array));

To sort an array with missing intermediate indices, with count the order is more secure. So 0 is the first index and count($jam_array) or sizeof($jam_array) return the decimal position of the array, namely, last index.

fvlgnn
  • 97
  • 2
  • 4
1

It's worth pointing out that the array in the question is a very special case, where all values are the same and keys are already in ascending order. If you have an array with different values and keys in any random order, and you want to sort it by key and reindex the keys, the existing answers will not do what you expect.

For example, if you have something like this:

[
    7 => 'foo',
    0 => 'bar',
    2 => 42
];

and you want to end up with this:

[
    0 => 'bar',
    1 => 42,
    2 => 'foo',
]

you can't just use array_values(), array_splice() or sort(), because you would end up with

[
    0 => 'foo',
    1 => 'bar',
    2 => 42,
]

Instead, you first need to sort the array based on the keys, using ksort(), and then reindex the keys using array_values():

$arr = [
    7 => 'foo',
    0 => 'bar',
    2 => 42
];

ksort($arr, SORT_NUMERIC);
$arr = array_values($arr);

Result:

[
    0 => 'bar',
    1 => 42,
    2 => 'foo',
]
Magnus
  • 17,157
  • 19
  • 104
  • 189
  • This task has creeped too far from the posted question. This question is in no way about sorting. This answer solves an "invented" (non-posted) concern. – mickmackusa Oct 10 '22 at 00:03
0

How to remove keys from php array?

was looking for a more elegant solution for this and got redirected here. my not-so-pretty solution might help someone else

you will use a second (temporary/buffer) array that will keep the filtered data

    // main array
    $main_arr = array(
        1      => 'ok',
        2      => 'ok',
        5      => 'discard',
        99     => 'discard',
        'a'    => 'ok',
        'b'    => 'red',
        'text' => 1.22,
        'zzz'  => true
    );

    $temp_arr = array(); // temporary array. will be unset later on
    
    // parse the main array
    foreach( $main_arr as $key => $value ) {
        if( $value != 'discard' ) {
            $temp_arr[$key] = $value; // retain the key=>value pairs
        }
    }
    
    // overwrite $main_arr only if there's a mismatch between the main/temporary arrays' key count
    if( count($main_arr) != count($temp_arr) ) {
        $main_arr = $temp_arr; // replace main array content with data from temporary array
    }
    
    unset($temp_arr); // free (some) memory
George-Paul B.
  • 544
  • 4
  • 7