Refer to the snippet below: $i=0; for($i=0;$i<=$n;$i++){ $var.$i=$_POST["query".$i]; } I just need to generate variables out of the loop. e.g. $var1,$var2,$var3... I will store some data on that variables for later printing. I've tried the snippet using the format above but it never worked. Any solution for this? * the loop maybe for or while
<?php # Some defined constant. $n = 4; # Loop until $i = 4 for($i=0;$i<=$n-1;$i++) { # Set the variable name. $var = 'var'.(string)$i; # Set the POST field to be a 'variable variable'; $$var = $_POST["query".$i]; } # Now, the data can be retrieved with 'var'.$i; echo $var0; // REMEMBER! STARTS AT ZERO because of $i. echo $var1; echo $var2; echo $var3; Code (markup):
Eugh, is there any reason why you're not using an array for this? Like this: $var[] = $_POST["query".$i]; Code (markup): That will push each POST item onto the array, so you will get: $var[0] = postitem1 $var[1] = postitem2 etc. That would be the way to do it in 99% of situations, that's what arrays are for!