How to create christmas tree algorithm in PHP

1

I'm doing the following code, however PHP does not add and assign zero:

<?php
$linha = "*";
for($i = 0; $i < 6; $i++){
    echo($linha)."<br>";
    $linha += "*"; //aqui o php nao soma
}
?> 

The output of this code was meant to be:

*
**
***
****

But it goes like this:

0
0
0
0
0
0

Can anyone help me?

    
asked by anonymous 29.09.2015 / 04:59

1 answer

4

You want to concatenate strings , for this you use . not + in php.

Just change the following line $linha += "*"; to $linha .= "*"; :

$linha = "*";
for($i = 0; $i < 6; $i++){
    echo($linha)."<br>";
    $linha .= "*";
}

A brief explanation:

The .= operator in PHP is used for concatenation of variables, exp: $a .= $b can be rewritten as: $a = $a . $b . And it is expected to have the following: string .= string .

The += operator in PHP is used for the arithmetic operation of sum of variables, exp: $a += $b can be rewritten as: $a = $a + $b . And it is expected to have the following: integer += integer .

Thus, with the arithmetic operator += , even though the value is in relatives, implying that it is a string and not a numeric value, the conversion from string to integer is done. As can be seen with the following test:

echo "<b>Teste com .= </b><br/><br/>";
$linha = "Isso é";
echo "Valor antigo: ". $linha." <br/>Tipo antigo: ".gettype($linha)."<br/><br/>";
$linha .= " um teste";
echo "Novo valor: ". $linha." <br/>Tipo novo: ".gettype($linha)."<br/><br/>";
echo "<b>Teste com +=</b><br/><br/>";
$linha = "Isso é";
echo "Valor antigo: ". $linha." <br/>Tipo antigo: ".gettype($linha)."<br/><br/>";
$linha += " um teste";
echo "Novo valor: ". $linha." <br/>Tipo novo: ".gettype($linha)."<br/><br/>";
echo "<b>Outro teste com +=</b><br/><br/>";
$linha = "4";
echo "Valor antigo: ". $linha." <br/>Tipo antigo: ".gettype($linha)."<br/><br/>";
$linha += "10";
echo "Novo valor: ". $linha." <br/>Tipo novo: ".gettype($linha)."<br/>";

This should print:

  

Test with. =

     

Old value: This is Old type: string

     

New value: This is a test New type: string

     

Test with + =

     

Old value: This is Old type: string

     

New value: 0 New type: integer

     

Another test with + =

     

Old value: 4 Old type: string

     

New value: 14 New type: integer

    
29.09.2015 / 05:05