2

Possible Duplicate:
In PHP, how do you change the key of an array element?

I am reading in a bunch of multi-dimensional arrays, and while digging through them I have noticed that some of the keys are incorrect.

For each incorrect key, I simply want to change it to zero:

from:

$array['bad_value']

to:

$array[0]

I want to retain the value of the array element, I just want to change what that individual key is. Suggestions appreciated.

Cheers

2
  • As has been said you can't have multiple keys with the same name e.g. 0. What is it you're trying to do? Is it acceptable to split these keys out into a separate array? Commented Nov 3, 2009 at 13:42
  • sorry, when i said 0, it just has to be numeric, so it could be 1 or 2 and so on. That isn't the problem, some of the keys are coming back with some weird stuff in them that I need to get rid of. Commented Nov 3, 2009 at 13:51

4 Answers 4

7

if you change multiple keys to 0 you will overwrite the values...

you could do it this way

$badKey = 'bad_value';
$array[0] = $array[$badKey];
unset($array[$badKey]);
Sign up to request clarification or add additional context in comments.

Comments

3

Bruteforce method:

$array[0] = $array['bad_value'];
unset($array['bad_value']);

4 Comments

yeah but since this array is part of a multidimensional array I need to maintain its position in its containing array
you can't maintain the position while changing the key - can you?
not unless the position is numeric, which it is.
nope. Even when numeric, the position might not be in order. Read up documentation on PHP Arrays and Internal Pointers. You can sort around the array, but the keys remain.
0
$array['0'][] = $array['bad_value'];
unset( $array['bad_value'] );

Then it will be an array in $array['0'] with values of broken elements.

Comments

-2

Well seeing as you said the keys can be changed to any numeric value how about this?

$bad_keys = array('bad_key_1', 'bad_key_2' ...);
$i = 0;
foreach($bad_keys as $bad_key) {
    $array[$i] = $array[$bad_key];
    unset($array[$bad_key]);
    $i++;
}

EDIT: The solution I gave was horrible and didn't really solve the problem as there are multiple bad keys, this should be better.

1 Comment

That's awful. There's absolutely no need to loop on the entire array. PHP perfectly knows how to get a named array element without looping the whole of it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.