How to update key value in an associative array PHP

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Update key value in array PHP

This article focuses on how to update key value in array PHP. Though the article includes three approaches, the second approach is the most efficient.

Introduction

PHP associative arrays are basically hash maps as they include key and value pairs. The keys are unique but mutable. Thus, we can update key value in array PHP, and that’s exactly what this article will focus on. Let’s begin.

#1 – Update key value in array PHP using a loop

The most obvious approach is using a loop. PHP foreach loop is convenient because it gives us easy access to key and value pairs. The following example will use a foreach loop to change key value in array PHP.

<?php
 
$students_score = [
   "Alison" => 10,
   "Liam"   => 9,
   "Jenny"  => 8,
   "Jamie"  => 7,
   "Ron"    => 6
];
 
 
function changeName($students_score, $oldName, $newName)
{
    foreach($students_score as $student=>$score)
    {
        if($student == $oldName)  
        {
            $students_score[$newName] = $score; // Only the keys are meant to be replaced.
            unset($students_score[$student]);   // Removes the old key and value.
        }
    }
 
    arsort($students_score);
    return $students_score;
}
 
$students_score = changeName($students_score, 'Jamie', 'James');
 
 
/*
Array
(
    [Alison] => 10
    [Liam] => 9
    [Jenny] => 8
    [James] => 7
    [Ron] => 6
)
*/
?>

The breakdown of the changeName() in the example is as follows.

  • It loops through the array and find the key that equals to the name that’s gonna be replaced.
  • Once it finds that key it assigns the associated score to the new key.
  • It then removes the old key and value because the array has the updated entry.
  • Finally, it sorts the array in descending order using the arsort function.

The array elements are placed by order of their insertion. That’s why using the PHP arsort helps in rearranging the scores. The output in the example confirms it. 

#2 – Update key value in array PHP using array_key_exists

Using a foreach loop is redundant because the array features direct indexing meaning that the array returns values for a given key. So, let’s cut the loop part and bring down the complexity further.

The following example uses the PHP array_key_exists to see if the key exists in the first. Otherwise, just returns the array unmodified.

<?php
 
$students_score = [
   "Alison" => 10,
   "Liam"   => 9,
   "Jenny"  => 8,
   "Jamie"  => 7,
   "Ron"    => 6
];
 
 
function changeName($students_score, $oldName, $newName)
{
    if(!array_key_exists($oldName, $students_score))
    {
        return $students_score;
    }
 
    $score = $students_score[$oldName]; //Get the score.
    $students_score[$newName] = $score; //New key with the score.
    unset($students_score[$oldName]);
    arsort($students_score);
    return $students_score;
}
 
$students_score = changeName($students_score, 'Jamie', 'James');
 
/*
Array
(
    [Alison] => 10
    [Liam] => 9
    [Jenny] => 8
    [James] => 7
    [Ron] => 6
)
*/
?>

Here’s how the function changes key value in array PHP.

  • It returns the array as it is, if the key to be replaced doesn’t exist.
  • Otherwise, it gets the score by the key – Direct Indexing.
  • It sets a new key in the array and assigns it the score.
  • It unsets the old key and value.
  • Finally, it sorts the array in descending order using the arsort function.

Compared to the loop approach, this approach is definitely more efficient in terms of complexity as it doesn’t need to traverse the whole array.

#3 – Update key value in array PHP using array_search

Although this approach isn’t more efficient than the second, we would try anyway. Let’s jump to the example, and we’ll explain everything in the breakdown that follows it.

<?php
 
$students_score = [
   "Alison" => 10,
   "Liam"   => 9,
   "Jenny"  => 8,
   "Jamie"  => 7,
   "Ron"    => 6
];
 
 
function changeName($students_score, $oldName, $newName)
{
    if(!array_key_exists($oldName, $students_score))
    {
        return $students_score;
    }
 
    $names = array_keys($students_score);
 
    $names[array_search($oldName, $names)] = $newName;
 
    return array_combine($names, $students_score);
}
 
$students_score = changeName($students_score, 'Jamie', 'James');
 
/*
Array
(
    [Alison] => 10
    [Liam] => 9
    [Jenny] => 8
    [James] => 7
    [Ron] => 6
)
*/
?>

Here’s the breakdown of this example.

  • The function uses the array_key_exists check as seen already.
  • It uses PHP array_keys to get an array of keys only.
  • It then searches through the keys array using array_search to find the key to be replaced.
  • Once found, the key is replaced by the newer one.
  • Finally using the array_combine, it combines the updated keys array with the values from the input array.

Luckily, we don’t have to use the sort function here as the order is unchanged. However, this approach has an overhead of multiple function calls. So, it may not be ideal to change key value in array PHP.

Conclusion

This article focuses on how to update key value in array PHP. Starting with a foreach loop approach, the article moves to a more efficient direct indexing approach. Finally, the article uses some popular PHP functions to change key value in an array. The direct indexing approach is the most efficient.

Hopefully, you’ve liked this article. Learn more about PHP at FuelingPHP

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.