Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change php variable name in a loop?

Lets say I have a variable called $file and the for loop: for($i=1; $i <= 5; $i++) {}

For each iteration of the for loop, the $i value will be appended to the $file variable name so after the for loop ends, I should have five variables: $file1, $file2, $file3, $file4, and $file5.

like image 414
user701510 Avatar asked Jun 04 '11 05:06

user701510


People also ask

How do you name a variable in PHP?

All variables in PHP start with a $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character _ . A variable name cannot start with a number. A variable name in PHP can only contain alpha-numeric characters and underscores ( A-z , 0-9 , and _ ).

What is $$ variable in PHP?

The $var_name is a normal variable used to store a value. It can store any value like integer, float, char, string etc. On the other hand, the $$var_name is known as reference variable where $var_name is a normal variable. The $$var_name used to refer to the variable with the name as value of the variable $var_name.

Which 3 are correct variable names in PHP?

A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive ( $age and $AGE are two different variables)


1 Answers

Use ${'varname'} syntax:

for($i=1; $i <= 5; $i++) {     ${'file' . $i} = $i; } 

However, it's often better to use arrays instead of this.

like image 135
Yuri Stuken Avatar answered Oct 04 '22 07:10

Yuri Stuken