0
$arr = ["250","250","500","500","250"];

Here is my $arr array. I want to replace 300 instead of 500.

Sample:

["250","250","300","300","250"]; //Output

Here is my code

$length = sizeof($arr);

for($i = 0; $i < $length; $i++)
{

 if($arr[$i] <= 300)
 {

 }
 else
 {
      $replace = array($i => "300");
      array_replace($arr, $replace);
 }

}
2
  • Please provide a question. It is not clear what you want to find out. Commented Jan 18, 2019 at 17:00
  • I want ["250","250","500","500","250"] this array replace to ["250","250","300","300","250"]; using for loop or foreach Commented Jan 18, 2019 at 17:02

2 Answers 2

3

You should use the str_replace() function, that allows you to replace a value with another one in both strings and arrays.

In your case it would be:

$arr = str_replace("500","300",$arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Just know this will replace the 500 in 5000 with 300 yielding 3000, 50015 to 30015, etc...
0

you could use array_replace(), but it works not by value, rather by position, and array_replace() returns a new array rather than mutating the original one.

you could modify the else part of your code like below, since you were not using the modified array;

 ....
 ....
 else
 {
  $replace = array($i => "300");
  $arr2 = array_replace($arr, $replace);
  var_dump($arr2);//this holds the replaced array
 }

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.