cgm225 Posted August 16, 2008 Share Posted August 16, 2008 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! Quote Link to comment https://forums.phpfreaks.com/topic/119934-replace-key-value-in-array/ Share on other sites More sharing options...
Psycho Posted August 16, 2008 Share Posted August 16, 2008 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; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/119934-replace-key-value-in-array/#findComment-617836 Share on other sites More sharing options...
nrg_alpha Posted August 16, 2008 Share Posted August 16, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/119934-replace-key-value-in-array/#findComment-617838 Share on other sites More sharing options...
thebadbad Posted August 16, 2008 Share Posted August 16, 2008 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>'; ?> Quote Link to comment https://forums.phpfreaks.com/topic/119934-replace-key-value-in-array/#findComment-617877 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.