A.Developer
A.Developer

Reputation: 43

How to replace array_value?

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

}

Upvotes: 0

Views: 70

Answers (2)

Shobi
Shobi

Reputation: 11451

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
 }

Upvotes: 0

J. Almandos
J. Almandos

Reputation: 347

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

Upvotes: 3

Related Questions