简体   繁体   中英

Built-in PHP function to reset the indexes of an array?

Example:

$arr = array(1 => 'Foo', 5 => 'Bar', 6 => 'Foobar');
/*... do some function so $arr now equals:
    array(0 => 'Foo', 1 => 'Bar', 2 => 'Foobar');
*/

Use array_values($arr) . That will return a regular array of all the values (indexed numerically).

PHP docs for array_values

array_values($arr);

To add to the other answers, array_values() will not preserve string keys. If your array has a mix of string keys and numeric keys (which is probably an indication of bad design, but may happen nonetheless), you can use a function like:

function reset_numeric_keys($array = array(), $recurse = false) {
    $returnArray = array();
    foreach($array as $key => $value) {
        if($recurse && is_array($value)) {
            $value = reset_numeric_keys($value, true);
        }
        if(gettype($key) == 'integer') {
            $returnArray[] = $value;
        } else {
            $returnArray[$key] = $value;
        }
    }

    return $returnArray;
}

Not that I know of, you might have already checked functions here

but I can imagine writing a simple function myself

resetarray($oldarray)
{
for(int $i=0;$i<$oldarray.count;$i++)
     $newarray.push(i,$oldarray[i])

return $newarray;
}

I am little edgy on syntax but I guess u got the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM