Jump to content

Archived

This topic is now archived and is closed to further replies.

cgm225

Replace key value in array...

Recommended Posts

If I have an array with a certain key value, how do I replace the value of that key?  Restated, I do not want to add another key and value, but, rather, replace an existing key's value with another value.

 

Thanks in advance!

Share this post


Link to post
Share on other sites

I don't believe you can do that directly. The only thing I know of that will natively change an array key is array_change_key_case() which only changes the case of all the keys in an array.  What's wrong with simply creating a new key with the target value and destroying the old key?

 

A simple function could do this for you:

 

<?php

function array_change_key(&$array, $old_key, $new_key)
{
    $array[$new_key] = $array[$old_key];
    unset($array[$old_key]);
    return;
}

?>

Share this post


Link to post
Share on other sites

Well, just access that particular key and assign it a new value.

 

So if you are using an associative array and you know the key's name:

 

$str = array('a' =>'I_am', 'b' =>'an', 'c'=>'array');
$str['c'] = 'elePHPant!'; // say you wanted to change the value of key 'c'
foreach($str as $val){
  echo $val . '<br />';
}

 

if it's an indexed array:

$str = array('PHP', 'simply', 'sucks!');
$str[2] = 'rocks!'; // simply target the appropriate index key and re-assign.
foreach($str as $val){
  echo $val . '<br />';
}

 

I would suggest googling PHP array topics and doing some tutorials to get a little more familiar with arrays and how they work.

Share this post


Link to post
Share on other sites

Or you could rebuild the array (and keep the element's order):

 

<?php
function replace_key($find, $replace, $array) {
$arr = array();
foreach ($array as $key => $value) {
	if ($key == $find) {
		$arr[$replace] = $value;
	} else {
		$arr[$key] = $value;
	}
}
return $arr;
}

//example
$array = array('test' => 0, 'replace this' => 1, 3 => 'hey');
echo '<pre>', print_r($array, true), '</pre>';
$array = replace_key('replace this', 'with this', $array);
echo '<pre>', print_r($array, true), '</pre>';
?>

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.