Can you use a variable that’s inside the for?

Asked

Viewed 674 times

1

For example. I am working with Heredoc and whenever I need to do a for, I have to close Heredoc to do the for then open the mentioned tag again.

Is there any way to query a variable within the is that will return all results to me? For example.:

$telefones = 3;
for($i = 0; $i < $telefones; $i++) {
     $numero_tel = $buscar_telefones[$i]['numero'];
     $todosNumeros = "telefone: $numero_tel";
}
echo <<< EOT
     $todosNumeros
EOT;

PRINT : telephone: 9999-9999 telephone: 9999-7777 telephone: 9999-8888

Thank you very much !

2 answers

5


Only declare the variable before, outside the for().

There are a few more changes that need to be made, as below:

$todosNumeros = "";
$telefones = 3;

for($i = 0; $i < $telefones; $i++) {
     $numero_tel = $buscar_telefones[$i]['numero'];
     $todosNumeros .= "telefone: " . $numero_tel . " ";
}
echo <<< EOT
     $todosNumeros
EOT;
  • This returning me error Parse error: syntax error, unexpected T_VAR

  • Sorry, I used a syntax of PHP4. See now.

  • I tried this way but he returned only one number. Did not return the three. Thanks for the help.

  • @Diegohenrique I made several corrections. See if now meets you.

  • 1

    @Gypsy Morrison Mendez is not required to create the variable before, outside the for. A variable created inside the for can be perfectly accessed from outside it.

  • It’s just that I went more by the title of the question, but you’re right.

Show 1 more comment

3

You can perfectly utilize, out of the for, any variable created within the context of for(), and it is not mandatory to create it before;

$telefones = 3;
for($i = 0; $i < $telefones; $i++) {
     $numero_tel = $buscar_telefones[$i]['numero'];
     $todosNumeros .= "telefone: $numero_tel ";
}

echo $todosNumeros;
  • You are correct. However, for what I need, I have to clean the variable, otherwise it will return me numbers that already existed in the previous ones. @Leofelipe Thank you so much for your help!

  • Yes, if the variable already exists from another context and has values, it should be reset to not impact the rules of your loop.

Browser other questions tagged

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