Skip to content

Instantly share code, notes, and snippets.

@Balamir
Created January 27, 2018 21:14
Show Gist options
  • Save Balamir/4b22d71569a65a2b9045beab97e54732 to your computer and use it in GitHub Desktop.
Save Balamir/4b22d71569a65a2b9045beab97e54732 to your computer and use it in GitHub Desktop.
This function can helps to replace an|multiple array key(s) with the new one.
<?php
/**
* Single or multiple array key changer.
*
* @author Abdullah M CEYLAN
* @author URI http://www.abdullahceylan.com
*
* @param {array} $array Old array
* @param {string | array} $old_key Old array keys that can be string or array
* @param {string | array} $new_key New array key(s) that can be string or array
* @return {array} New array with replaced keys
*/
function change_array_key( $array, $old_key, $new_key) {
if(!is_array($array)){ print 'You must enter a array as a haystack!'; exit; }
if (is_array($old_key) && !is_array($new_key)) {
print 'You must enter a array as a new_key!'; exit;
} elseif (is_array($new_key) && !is_array($old_key)) {
print 'You must enter a array as a old_key!'; exit;
}
$new_array = $array;
if (is_array($old_key)) {
$keyfound = false;
$key_index = 0;
foreach ($old_key as $key) {
if (!array_key_exists($key, $array)){
$key_index++;
continue;
}
$keyfound = true;
$new_array = search_array_and_replace($new_key[$key_index], $key, $new_array);
$key_index++;
}
if (!$keyfound) {
return $array;
} else {
return $new_array;
}
} elseif (!array_key_exists($old_key, $array)){
return $array;
}
return search_array_and_replace($new_key, $old_key, $array);
}
function search_array_and_replace($new_key, $old_key, $array) {
$keyPosition = array_search($old_key, array_keys($array));
$arrayBeforeKey = array_slice($array, 0, $keyPosition);
$arrayAfterKey = array_slice($array, $keyPosition + 1);
$arrayReplaced = array($new_key => $array[$old_key]);
return $arrayBeforeKey + $arrayReplaced + $arrayAfterKey;
}
?>
@Balamir
Copy link
Author

Balamir commented Jan 27, 2018

Example - 1 (Multiple key changing):

$old_array = array(
  'ELMA' => 'Elma sepeti',
  'ARMUT' => 'Armut sepeti',
  'MUZ' => 'Muz sepeti'
);

$new_array = change_array_key(
  $old_array,
  array('ELMA', 'MUZ'),
  array('ELMA_AGACI', 'MUZ_BAHCESI')
);

Result - 1:

array(
  'ELMA_AGACI' => 'Elma sepeti',
  'ARMUT' => 'Armut sepeti',
  'MUZ_BAHCESI' => 'Muz sepeti'
);

Example 2 (Single key changing):

$new_array = change_array_key(
  $old_array,
  'ARMUT',
  'ARMUT_BAHCESI'
);

Result - 2:

array(
  'ELMA' => 'Elma sepeti',
  'ARMUT_BAHCESI' => 'Armut sepeti',
  'MUZ' => 'Muz sepeti'
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment