Search code examples
phparraysexplodearray-key

php explode and force array keys to start from 1 and not 0


I have a string that will be exploded to get an array, and as we know, the output array key will start from 0 as the key to the first element, 1 for the 2nd and so on.

Now how to force that array to start from 1 and not 0?

It's very simple for a typed array as we can write it like this:

array('1'=>'value', 'another value', 'and another one');

BUT for an array that is created on the fly using explode, how to do it?

Thanks.


Solution

  • $exploded = explode('.', 'a.string.to.explode');
    $exploded = array_combine(range(1, count($exploded)), $exploded);
    var_dump($exploded);
    

    Done!