Cheerio
Cheerio

Reputation: 1240

Rename keys in array PHP

Hey all: I have this array:

$names = array('a','b','c'); 
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.

Upvotes: 0

Views: 3003

Answers (4)

Email
Email

Reputation: 2425

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.

Upvotes: 0

Cheerio
Cheerio

Reputation: 1240

I just found a solution:

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

Upvotes: 1

Dan Grossman
Dan Grossman

Reputation: 52372

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.

Upvotes: 2

Philippe Gerber
Philippe Gerber

Reputation: 17836

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

Upvotes: 3

Related Questions