Sometimes code needs you to generate PHP variables on the fly. This can mostly be avoided but if you want to it's very easy.
To create a dynamic variable you naturally need to start with a string to name the variable. You can get this by generating a number with a for loop, reading it in from a database or whichever input you're getting it from. As you know a variable name cannot start with certain characters and mainly needs to start with a letter (very basic explanation).
So straight to the code. We will do a simple example of generating a variable with a dynamic name.
//this will loop ten times starting with 0 and ending with 4 for ($i = 0; $i < 5; $i++){ $stringVariableName = 'myVar'.$i; $$stringVariableName = $i; }
This will generate the following php code:
$myVar0 = 0; $myVar1 = 1; $myVar2 = 2; $myVar3 = 3; $myVar4 = 4;
PLEASE NOTE: You cannot declare the variable $this as it is one of the reserved words in PHP.
By PHPin24 @ 2008-11-24 00:15:37
|