Reputation: 43
$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
$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
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
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