Search code examples
phparraysarray-key

PHP, how do you change the key of an array element?


Hello guys, and Happy new year!

How can I add keys to this array

$my_array = array( [0] => 703683 [1] => 734972 [2] => 967385 )

So I would like to add a single key to all values example:

   $copy_array = array( ['id'] => 703683 ['id'] => 734972 ['id'] => 967385 )

I tried this solution:

 new_arr = [];
foreach ($my_array as $key => $value) {
    // code..
    $new_arr['id'] = $value ;
  }

Output:

( [id] => 703683 )

Solution

  • You can't. An array key is identifying the element it represents. If you set 'id' to be a specific value, then you set it to be another specific value, then you override the former with the latter. Having separate values as ids is self-contradictory anyway, unless they identify different objects. If that's the case, then you can change your code to

     new_arr = [];
    foreach ($my_array as $key => $value) {
        // code..
        $new_arr[] = ['id' => $value] ;
      }
    

    or even

     new_arr = [];
    foreach ($my_array as $key => $value) {
        // code..
        $new_arr[$value] = ['id' => $value] ;
      }
    

    but the only use of such a change would be if they have other attributes, which are not included in the codes above, since your question does not provide any specific information about them if they exist at all. If everything is only an id, then you might as well leave it with numeric indexes.