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

前端 未结 4 737
悲哀的现实
悲哀的现实 2021-01-13 04:50

Example:

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


        
相关标签:
4条回答
  • 2021-01-13 04:57

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

    PHP docs for array_values

    0 讨论(0)
  • 2021-01-13 05:06

    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;
    }
    
    0 讨论(0)
  • 2021-01-13 05:08
    array_values($arr);
    
    0 讨论(0)
  • 2021-01-13 05:09

    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.

    0 讨论(0)
提交回复
热议问题