0

I've done some searches but can't seem to find someone with the same problem as I. I can't figure out how to change the key of an array that's beeing pushed into another array.

Example.

    $array1
    $array2

    array_push($array1, $array2);

    $array1 [
       "0" [
        //the data in array2
       ]
    ]

I want to change the key value where it says "0". Anyone know how I can do that?

2
  • 2
    Just don't use array_push. Or do you want to change the kay after the element has been added? Commented Sep 9, 2015 at 12:38
  • Hi @fschmengler! I didn't think about that solution, thanks! :) Commented Sep 9, 2015 at 14:01

2 Answers 2

2

You can not change a key directly. Instead you would insert the same data under the new key and remove the old key.

For example:

$array['new_key'] = $array['old_key'];
unset($array['old_key']);

Alternatively, instead of using array_push(), you can set the array key directly:

$array1['new_key'] = $array2;

I encourage you to read the PHP Arrays docs as arrays are a foundational element of PHP.

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

Comments

1

Maybe you can try this?

$array1['your-key'] = $array2;

1 Comment

Oh, that was really smart. It fixed everything. Don't know how I couldn't think about this solution! Thanks!

Your Answer

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