I have a question and it is the following.
My goal is to replace the values of all the fruits to increase the price by 5%:
// precios originales
$precios = array (
"frutas" => array (
"manzanas" => 15,
"peras" => 5,
"naranjas" => 3,
),
"verduras" => array (
"clave" => 15,
"clave2" => 5,
"clave3" => 3,
)
);
// Los precios de frutas suben 5%
foreach ($precios['frutas'] as $clave => $valor) {
$nuevovalor = $valor*5/100+$valor;
$valor = ceil($nuevovalor);
}
// los precios de las verduras suben un 3%
foreach ($precios['verduras'] as $clave => $valor) {
$nuevovalor = $valor*3/100+$valor;
$valor = ceil($nuevovalor);
}
My idea is to use the function array_replace
but so far, nothing I have done seems to work to replace the values with the new prices, this in case the new prices are well resolved with that function, your idea will be welcome, greetings.
You got very complicated. Instead of looping through it with a
foreach
, loop through the array with afor
and you can index the array to manipulate its data.With
foreach
you can do it but you must declare an incremental variable to use as an index. Also don't use variable names as indices, because you won't be able to iterate through them dynamically:I prefer to modify the array on itself instead of using
array_replace
. However, I left you both solutions. Try IDEONEcomments:
=
it is the way of making assignments in the "traditional" sense: what is to the right of=
is assigned to what is on the left; while it=>
works the other way around and is used in "for" loops. on the other hand, multiplying a value by a decimal value gives you the percentage, with 0.05 being equal to 5% and 1 being equal to 100%. when adding both values I have 105%, which is the same: an increase of 5%.You can take advantage of the benefits of PHP 5.5 and use
array_map
and a lambda . The code is quite simplified:Even the second part of the code can be simplified even more, in case you have another type of element with its price besides fruits and vegetables: