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
Why rename? Just use $key + 1
when needed.
answered Dec 2, 2010 at 11:55
1 Comment
Cheerio
I'll use the $key in as [$key] so I can't added a value to it.
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
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
David Kuridža
Your solution does not match the question :)
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
lang-php