7

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?

Galen
30.2k9 gold badges75 silver badges90 bronze badges
asked Nov 20, 2011 at 2:29

2 Answers 2

23

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.

answered Nov 20, 2011 at 2:31
Sign up to request clarification or add additional context in comments.

Comments

0

In case you want to have an inline solution you can use array_replace or array_replay_recrusive depending on which suits you best.

$replaced_arr = array_replace([
 'key' => 'old_value',
 0 => 'another_untouched_value'
 ],[
 'key' => 'new_value'
 ]);

It would be best if your array is key/value pair

answered Jan 3, 2021 at 23:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.