php change array key code example
Example 1: change key with the value php
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
Example 2: array key value php
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Example 3: how to replace array key php
function array_replace_key($search, $replace, array $subject) {
$updatedArray = [];
foreach ($subject as $key => $value) {
if (!is_array($value) && $key == $search) {
$updatedArray = array_merge($updatedArray, [$replace => $value]);
continue;
}
$updatedArray = array_merge($updatedArray, [$key => $value]);
}
return $updatedArray;
}
$user = ['name' => 'Donald Pakkies', 'age' => 22];
var_dump(array_replace_key('name', 'full_name', $user));