Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a specific key's value in an array in php?

I have a an array that has 3 values. After the user pushes the submit button I want it to replace the the value of a key that I specify with another value.

If I have an array with the values (0 => A, 1 => B, 2 => C), and the function is run, the resulting array should be (0 => A, 1 => X, 2 => C), if for example the parameter for the function tells it to the replace the 2nd spot in the array with a new value.

How can I replace a specific key's value in an array in php?

like image 719
zeckdude Avatar asked Nov 20 '11 02:11

zeckdude


People also ask

How can I remove a specific item from an array PHP?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array.

How do you change the key of an associative array?

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.


1 Answers

If you know the key, you can do:

$array[$key] = $newVal;

If you don't, you can do:

$pos = array_search($valToReplace, $array);
if ($pos !== FALSE)
{
   $array[$pos] = $newVal;
}

Note that if $valToReplace is found in $array more than once, the first matching key is returned. More about array_search.

like image 74
Aurelio De Rosa Avatar answered Sep 23 '22 17:09

Aurelio De Rosa