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.

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

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.

Comments

1

I just found a solution:

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

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.

Comments

Your Answer

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.