开发者

Rename keys in array PHP

Hey all: I have this array:

$names = array('a','b','开发者_如何学Cc'); 
foreach($names as $key => $value ) {
    echo $key;
}

where a, b, c come from a name[] field

The input is:

0
1
2

There is an array function to replace the output result as:

1
2
3

I want to rename the first key because I'll insert theme into a mysql table.


Why rename? Just use $key + 1 when needed.


for ($i = count($names) - 1; $i >= 0; $i--) 
    $names[$i + 1] = $names[$i];
unset($names[0]);

or

array_unshift($names, 0); 
unset($names[0]);

or

Just use $key+1 in your query rather than changing the array.


I just found a solution:

$names = array(1 => 'a','b','c'); 
foreach($names as $key => $value ) {
    echo $key;
}


Maybe this if you want to increase all by 1:

$names = array('a','b','c'); 
foreach($names as $key => $value ) {
    $key = $key+1;
}

or

$names = array('a','b','c'); 
foreach($names as $key => $value ) {
    if($key==1) {
        $key = $key+1;
    }
}

but the second one would not make any sense since it would just be replaced by the second array element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜