0

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.

asked Dec 2, 2010 at 11:54

4 Answers 4

3

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

answered Dec 2, 2010 at 11:55

1 Comment

I'll use the $key in as [$key] so I can't added a value to it.
2
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.

answered Dec 2, 2010 at 11:56

Comments

1

I just found a solution:

$names = array(1 => 'a','b','c'); 
foreach($names as $key => $value ) {
 echo $key;
}
answered Dec 2, 2010 at 11:57

1 Comment

Your solution does not match the question :)
0

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.

TazGPL
3,7462 gold badges41 silver badges60 bronze badges
answered Dec 2, 2010 at 11:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.