Multiplying values within a for

Asked

Viewed 535 times

3

I’m using the for to generate a loop of 4 repetitions! Inside this loop I do a simple numerical multiplication.

<?php

    echo "Resultado: ";
    for($loop = 1; $loop <= 4; $loop += 1)      

        {
            echo ($loop * 10)." ";
        }
?>

Resultado: 10 20 30 40

And I don’t know how, but I’d like the result to be

1 10 50 100

How to do this!?

4 answers

1

Based on your code would look like this!

$str = [50,0];
for($i=1; $i<=4; $i++) {

    if($i==1){
        $output = $i ." ";
    } else {        
        $next = array_sum($str);    
        array_shift($str);
        array_push($str,$next);     
        if($i==2){
            $output .= ($next/5) ." ";
        } else {
            $output .= $next." ";
        }       
    }

}

echo $output;

output

1 10 50 100

1


Only use a multiplier for each result, since it is predefined:

<?php

$m = array(0, 1, 5, 16.66666666666667, 25);

echo "Resultado: ";
for ($loop = 1; $loop <= 4; $loop += 1) {
    echo ($loop * $m[$loop]) . " ";
}

?>
  • The simplicity of the code helped a lot!

0

has another option... Also right

    <?php

echo "Resultado: ";

$resultado = array();

$valorInicial = 1;

$valor = $valorInicial;

$multiplicador = 10;

for($loop = 1; $loop <= 4; $loop += 1)  {    

    $valor = $valor * $multiplicador;

    array_push($resultado, $valor);

    $multiplicador =  $multiplicador / 2;

    $multiplicador = (int)$multiplicador;

} echo $valorInicial." ".$resultado[0]." ".$resultado[1]." ".$resultado[2];

?>

0

I could not imagine a better application than this below because the multipliers are 1,10,5 and 2... But it worked

take a look:

<?php

echo "Resultado: ";

$resultado = array();

$valor = 1;

for($loop = 1; $loop <= 4; $loop += 1)  {    

    if($loop == 1){

        $valor = $valor * 1;

    }

    if($loop == 2){

        $valor = $resultado[0] * 10;

    }

    if($loop == 3){

        $valor = $resultado[1] * 5;

    }

    if($loop == 4){

        $valor = $resultado[2] * 2;

    }


    array_push($resultado, $valor);

} echo $resultado[0]." ".$resultado[1]." ".$resultado[2]." ".$resultado[3];

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.