在PHP中循环传递变量

I have a simple code that goes like this

<?php

echo $passer;

for($i=1; $i<=5; $i++){
    $msg = $i;
}

$passer = $msg;

?>

My aim is to display the result above the loop. Is there a way to pass the value of $msg so it will be displayed above the loop? Currently the output is:

Undefined variable: passer

First you are getting error Undefined variable: passer. because you are using variable without defining. So define variable before using:

$passer = 0; //defining variable 
echo $passer;// you are getting error here

for($i=1; $i<=5; $i++){
    $msg = $i;
}

$passer = $msg;

Above code will not give you output as you expecting. because you are echoing $passer before initializing it. Try something like this:

for($i=1; $i<=5; $i++){
    $msg = $i;
}

$passer = $msg;//initializing first
echo $passer;//output 5

Still in above solution i am echoing $passer after processing of for loop.

Because parser follows top to bottom approach so its impossible output above loop.

$msg = array();
for($i=1; $i<=5; $i++){
  $msg[] = $i;
}

$passer = $msg;
print_r($passer);

No One Language can output value before define that.

but you can like this to get your result.

<?php ob_start() ?>
  ##passer##
  <?php
    for($i=1; $i<=5; $i++){
        $msg = $i;
    } ?>
<?php echo str_replace("##passer##", $msg, ob_get_clean()) ?>