Multiplying values within a for

3

To using the for to generate a loop of 4 reps! Inside this loop I make a very simple numerical multiplication.

<?php

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

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

Resultado: 10 20 30 40

And I do not know how, but I would like the result to be

1 10 50 100

How to do this!?

    
asked by anonymous 30.05.2015 / 23:13

4 answers

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]) . " ";
}

?>
    
31.05.2015 / 04:40
1

Based on your code it 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
    
31.05.2015 / 06:03
0

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

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

?>
    
31.05.2015 / 04:26
0

It has another option ... It works too.

    <?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];

?>
    
31.05.2015 / 04:55