0

I have an array that contains year as follows. This key is going to be dynamic. NowI want to replace new_2018 to "2018".

$array = array(
    array(
        "new_2018" => "john",
    )
);

I have tried following approach. This is also working fine. But regarding quality I am not sure. Can anybody help me improve the quality of this code.

$newArr = array();
foreach ($array as $value) {
    foreach($value as $key => $val) {
        list($a, $year) = explode('_', $key);
        $newArr[][$year] = $val;
    }
}
user1687891
  • 794
  • 2
  • 14
  • 30
  • 1
    Your data structur seems a bit weird. Why do you add `new_` when you want to remove it?... what if you split your data to year, status and name instead ? – B001ᛦ Jan 21 '19 at 14:13
  • 1
    this new_ is coming from query which I am not allowed to modify – user1687891 Jan 21 '19 at 14:14
  • Possible duplicate of [In PHP, how do you change the key of an array element?](https://stackoverflow.com/questions/240660/in-php-how-do-you-change-the-key-of-an-array-element) – Maksym Fedorov Jan 21 '19 at 14:15
  • 1
    I don't see any problem with your code – executable Jan 21 '19 at 14:16
  • @MaximFedorov yes it can be duplicate but in my case I new_2018 is not fixed.. it can be any value with new_ – user1687891 Jan 21 '19 at 14:16
  • @executable if not problem then thats ok . because i saw in SO other using array_walk and pointer so I thought my code is not good – user1687891 Jan 21 '19 at 14:18

1 Answers1

0

it is ugly, but... and be careful with accessing by reference - don't forget to unset the variable:

<?php
$array = array(
    array(
        "new_2018" => "john",
    )
);

foreach ($array as &$value) {
    foreach($value as $key => $val) {
        $newKey = str_replace("new_", "", $key);
        $value[$newKey] = $val;
        unset($value[$key]);
    }
}
unset($value);

var_dump($array);
myxaxa
  • 1,391
  • 1
  • 8
  • 7