Jump to content

Replace key value in array...


cgm225

Recommended Posts

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;
}

?>

Link to comment
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.

Link to comment
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>';
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.