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

Community
  • 1
  • 1
Evernoob
  • 5,551
  • 8
  • 37
  • 49
  • 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? – RMcLeod Nov 03 '09 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. – Evernoob Nov 03 '09 at 13:51

4 Answers4

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]);
NDM
  • 6,731
  • 3
  • 39
  • 52
3

Bruteforce method:

$array[0] = $array['bad_value'];
unset($array['bad_value']);
mauris
  • 42,982
  • 15
  • 99
  • 131
  • yeah but since this array is part of a multidimensional array I need to maintain its position in its containing array – Evernoob Nov 03 '09 at 13:49
  • you can't maintain the position while changing the key - can you? – mauris Nov 03 '09 at 14:09
  • not unless the position is numeric, which it is. – Evernoob Nov 03 '09 at 15:16
  • 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. – mauris Nov 03 '09 at 16:53
0
$array['0'][] = $array['bad_value'];
unset( $array['bad_value'] );

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

silent
  • 3,843
  • 23
  • 29
-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.

RMcLeod
  • 2,561
  • 1
  • 22
  • 38
  • 2
    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. – Damien MATHIEU Nov 03 '09 at 14:14