Vera
Vera

Reputation: 105

Remove gaps in array indexes

This array has no [0] and [2] keys.

Array
(
[1] => 5.2836

[3] => 2.5749

[4] => 134.19

[5] => 5.8773

[6] => 1.3504
....

How can I change it to:

Array
(
[0] => 5.2836

[1] => 2.5749

[2] => 134.19

[3] => 5.8773

[4] => 1.3504
....

Is there any inbuilt function for such a task in php?

Upvotes: 1

Views: 113

Answers (2)

Paul
Paul

Reputation: 1545

You are not really sorting, it looks like you want to reassign keys to the values. try this:

<?php
    $array = array( 1 => 5.2836,  3 => 2.5749,  4 => 134.19,  5 => 5.8773,  6 => 1.3504 );
    $x=0;
    foreach($array as $key => $val){
        $new_array[$x] = $val;
        $x++;
    }
    echo "<pre>";
    print_r($new_array);
    echo "</pre>";
?>

Upvotes: -1

Felix Kling
Felix Kling

Reputation: 816384

Use array_values().

... returns all the values from the input array and indexes numerically the array.

Note this is not sorting or ordering the keys, it is reindexing the array.

Upvotes: 9

Related Questions