First thing you need to understand is the difference between printing some information to the output (eg. echo
) and assigning values to variables.
Your function just prints variable names to the output. However, these are strings. String is not equal to a piece of code once the program is running. This is the very basics of any sort of programming, and you must not try to do anything until variables are perfectly clear to you.
Now a solution. Since your variables are global, you can access them via php's $GLOBALS
array. This would look like this:
$str1 = "a";
$str2 = "b";
$str3 = "c";
function createArray($name, $count) {
$return_array = array();
for($i=0; $i<$count; $i++) {
$return_array[$name.($i+1)] = $GLOBALS[$name.($i+1)];
}
return $return_array;
}
print_r(createArray("str", 3));
Generally, what you're doing is absurd. If you wan't to store some data so that all the data can be accessed, start with an array:
array("a", "b", "c");
or
array("str1"=>"a", ...);
Also, many beginners tend to like the "evil" function. You could do it too. eval()
turns a string to a piece of code. But, it's always a bad solution and I've always learned a better one when I learned more about programming. However, you can't know everything from the beginning, so here is a way how to produce most dangerous and insecure codes:
function createArray($name, $count) {
$return_array = array();
for($i=0; $i
This is really dangerous and will cause trouble.
Using $$
syntax
I think that $$
approach proposed by ManiacTwister is the best. You can even turn a complicated string to a variable:
echo ${"static_text" . $string};
However, again, why not use arrays? This features should serve for debug purposes.
Note on variable scopes.
However, the variable scopes might be confusing, see an example:
$x = 666;
function printvar($name) {
global $$name; //Get the variable from global scope t the function scope
echo $$name; //if $name = "x" this evaluates into echo $x
echo "
"; //New line
}
printvar("x"); //Prints 666
function aFunction() {
$x = 13; //This $x only exists betvween {} and has nothing to do with global $x = 666
printvar("x"); //Still prints 666!
}