How to create a Christmas tree algorithm in PHP

Asked

Viewed 219 times

1

I am making the following code, but 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 to be:

*
**
***
****

But it comes out like this:

0
0
0
0
0
0

Can someone help me?

1 answer

4


You’re trying to concatenate strings, for this you use the . not the + in php.

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

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

A brief explanation:

The operator .= in PHP is used for variable concatenation, Exp: $a .= $b can be rewritten as: $a = $a . $b. And you’re supposed to have the following: string .= string.

The operator += in PHP is used for arithmetic variable sum operation, Exp: $a += $b can be rewritten as: $a = $a + $b. And you’re supposed to have the following: integer += integer.

Thus, with the arithmetic operator +=, however much the value is in relatives, implying that it is a string and not a numerical value, the conversion of string for integer. 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

  • Thank you Marcelo Bonifazio

  • 1

    @Eversonsouzadearaujo se a resposta resolver inteiramente seu pergunta, remember to vote positive and mark the question as accepted by clicking the green light below the voting mechanism.

  • when I click says I don’t have permission

  • @Eversonsouzadearaujo To vote you already have, I think to accept the answer has a minimum time that has to wait. This was very fast right. :)

  • 1

    that’s right@gustavox worked, obg

Browser other questions tagged

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