Question

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.

Was it helpful?

Solution

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

Done!

OTHER TIPS

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);
}
$somearray = explode(",",$somestring);

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

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

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

$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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top