1

I need to find and replace an element in an array. Is there any single php function for this?

1
  • Can you specify what the input is and what output you want Commented Feb 3, 2012 at 10:01

3 Answers 3

1

I don't know of any simple function for finding and replacing in arrays, but you could always do something like:

$key = array_search($oldValue, $myArray);
if ($key) $myArray[$key] = $newValue;
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply use array_splice.

See example

$input = array("red", "green", "blue", "yellow");
array_splice($input, -2, 1, array("orange", "maroon"));
// $input is now array("red", "green", "orange", "maroon","yellow")

1 Comment

Your solution does not solve the problem of finding the element to be replaced.
0

Try This:

<?php
$myArray = array("John","William","Henry","Tom","Peter");
$newArray = array_splice($myArray, 2, 1, "Susan");
foreach($myArray as $key => $value) {
    echo "$key - $value <br />";
}
?> 

Comments

Your Answer

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.