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

9k Views Asked by At

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.

6

There are 6 best solutions below

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

Done!

1
On
$somearray = explode(",",$somestring);

foreach($somearray as $key=>$value)
{
   $otherarray[$key+1] = $value;
}

well its dirty but isn't that what php is for...

0
On

Nate almost had it, but needed a temporary variable:

$someArray = explode(",",$myString);
$tempArray = array();

foreach($someArray as $key=>$value) {
   $tempArray[$key+1] = $value;
}
$someArray = $tempArray;

codepad example

1
On
$array = array('a', 'b', 'c', 'd');

$flip = array_flip($array);
foreach($flip as &$element) {
    $element++;
}
$normal = array_flip($flip);
print_r($normal);

Try this, a rather funky solution :P

EDIT: Use this instead.

$array = array('a', 'b', 'b', 'd');
$new_array = array();

$keys = array_keys($array);
for($i=0; $i<count($array); $i++) {
    $new_array[$i+1] = $array[$i];
}
print_r($new_array);
0
On

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);
}
0
On

I agree with @ghoti that this task is probably an XY Problem. I can't imagine a valid/professional reason to start keys from 1 -- I've never needed this functionality in over 10 years of development. I'll offer a compact looping approach, but I'll probably never need it myself.

After instatiating a counter which is one less than the desired first key, you can use a body-less foreach() as a one-liner.

Code: (Demo)

$i = 0;
$result = [];
foreach (explode('.', 'a.string.to.explode') as $result[++$i]);
var_export($result);