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; } } 
6
  • 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 ? Commented Jan 21, 2019 at 14:13
  • 1
    this new_ is coming from query which I am not allowed to modify Commented Jan 21, 2019 at 14:14
  • Possible duplicate of In PHP, how do you change the key of an array element? Commented Jan 21, 2019 at 14:15
  • 1
    I don't see any problem with your code Commented Jan 21, 2019 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_ Commented Jan 21, 2019 at 14:16

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.