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

好久不见. 提交于 2019-12-08 17:29:40
$exploded = explode('.', 'a.string.to.explode');
$exploded = array_combine(range(1, count($exploded)), $exploded);
var_dump($exploded);

Done!

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!