Dynamic Variables in PHP
June 13, 2014



In PHP, and especially when using Database operations like mysqli functions, you will want to create dynamic variable names. Luckily PHP makes this an extremely mundane task to accomplish.

First let’s take a look at a simple example so we understand the basic concept of how to do dynamic variables. Following that we can take a look at a more complex, but also more realistic example involving variable’s from a database.

For our first example, we will be adding a prefix to a collection of variables. In order to use a variable in the variable name declaration, we simply surround the declaration with { … }. Take a look at the following example:

The output should then be:

First Variable
Second Variable
Third Variable

This example shows just how easy it is to create dynamically named variables. Next we will take a look at a slightly more complicated but more practical use of dynamic variables.

As you can see, in this example we use the dynamic variables to obtain more information about the subject, their title. This application can be used with many database applications where data overlaps but is not necessarily organized. I like to think of it as almost a type of search that you can use.

As always thank you for reading and please share it around as much as you can! Please feel free to put any questions, suggestions, or ideas in the comments section below. I would really like to know what other kind of tutorials everyone wants me to make, so let me know!


Comments