PHP reindex array?

PhpArraysIndexing

Php Problem Overview


I have array that i had to unset some indexes so now it looks like

$myarray [0] a->1
         [1] a-7 b->3
         [3] a-8 b->6
         [4] a-3 b->2

as you can see [2] is missing all i need to do is reset indexes so they show [0]-[3].

Php Solutions


Solution 1 - Php

Use array_values.

$myarray = array_values($myarray);

Solution 2 - Php

$myarray = array_values($myarray);

array_values

Solution 3 - Php

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

Solution 4 - Php

This might not be the simplest answer as compared to using array_values().

Try this

$array = array( 0 => 'string1', 2 => 'string2', 4 => 'string3', 5 => 'string4');
$arrays =$array;
print_r($array);
$array=array();
$i=0;
    foreach($arrays as $k => $item)
    {
    $array[$i]=$item;
        unset($arrays[$k]);
        $i++;

    }

print_r($array);

Demo

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMrWhddite333View Question on Stackoverflow
Solution 1 - PhpAlex TurpinView Answer on Stackoverflow
Solution 2 - PhpAlfwedView Answer on Stackoverflow
Solution 3 - PhpDrasillView Answer on Stackoverflow
Solution 4 - PhpkrishnaView Answer on Stackoverflow