First of all, the if
is not a good example, because you can "create" the variable only once, even outside:
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
if( $id ):
/* Código que usa o $id, sem "criar" de novo */
endif;
But in a while
already complicates, so I’ll use this as an example:
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
In this case, not only is it correct, but it is a example taken from the PHP manual.
Since in the while
not only is it a common case, but often necessary, I see no reason not to use in the if
. In the end, readability is always the most important thing. And for that, it only depends on the context where you will use it. In the above example there was certainly no gain in separating the lines.
If you have any PSR saying otherwise, you have to fix the PSR instead of complicating the code.
What would be the version of this code without the if? sometimes is last other than xD
– rray
I think it is good to put the question of PSR in the title, because the rest merely depends on opinion. If you are going to use the information, the strange thing would be to just not create the variable. Although in the case of
if
you could create before.– Bacco
If it wasn’t for the poor people who use
while($busca=mysql_fetch_array($sql))
– Guilherme Lautert
I believe it is valid, but to certain things you can use the
&&
or||
before creating two conditions in sequence, but goes from the solution to solving....– Daniel Nicodemos
There’s no problem, it goes from the need to do this.
– Ivan Ferrer