how to change the array key to start from 1 instead of 0

后端 未结 10 2186
夕颜
夕颜 2020-12-05 02:09

I have values in some array I want to re index the whole array such that the the first value key should be 1 instead of zero i.e.

By default in PHP the array key st

10条回答
  •  無奈伤痛
    2020-12-05 02:40

    $alphabet = array("a", "b", "c");
    array_unshift($alphabet, "phoney");
    unset($alphabet[0]);
    

    Edit: I decided to benchmark this solution vs. others posed in this topic. Here's the very simple code I used:

    $start = microtime(1);
    for ($a = 0; $a < 1000; ++$a) {
        $alphabet = array("a", "b", "c");
        array_unshift($alphabet, "phoney");
        unset($alphabet[0]);
    }
    echo (microtime(1) - $start) . "\n";
    
    
    $start = microtime(1);
    for ($a = 0; $a < 1000; ++$a) {
        $stack = array('a', 'b', 'c');
        $i= 1;
        $stack2 = array();
        foreach($stack as $value){
            $stack2[$i] = $value;
            $i++;
        }
        $stack = $stack2;
    }
    echo (microtime(1) - $start) . "\n";
    
    
    $start = microtime(1);
    for ($a = 0; $a < 1000; ++$a) {
        $array = array('a','b','c');
    
        $array = array_combine(
            array_map(function($a){
                return $a + 1;
            }, array_keys($array)),
            array_values($array)
        );
    }
    echo (microtime(1) - $start) . "\n";
    

    And the output:

    0.0018711090087891
    0.0021598339080811
    0.0075368881225586
    

提交回复
热议问题