Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 795
medk Avatar asked Mar 18 '26 14:03

medk


2 Answers

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

Done!

like image 97
CodeAngry Avatar answered Mar 20 '26 08:03

CodeAngry


Just use a separator to create a dummy element in the head of the array and get rid of it afterwards. It should be the most efficient way to do the job:

function explode_from_1($separator, $string) {
    $x = explode($separator, $separator.$string);
    unset($x[0]);
    return $x;
}

a more generic approach:

function explode_from_x($separator, $string, $offset=1) {
    $x = explode($separator, str_repeat($separator, $offset).$string);
    return array_slice($x,$offset,null,true);
}
like image 27
Eineki Avatar answered Mar 20 '26 08:03

Eineki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!