Here i have an array in PHP. how can i assign array1 value as a variable name? i want to call the variable by the name in the array.
$array1 = array("comp1", "comp2", "comp3");
for example: when i use foreach loop to loop, i want the variable name to be concatenate with the value in the array.
$var + comp1 >>> ($varcomp1)
$var + comp2 >>> ($varcomp2)
or even
$varcomp + 1 >>> ($varcomp1)
$varcomp + 2 >>> ($varcomp2)
this may sound stupid but i have no idea if this is even possible. or is there any other better way to do this so that i can call the variables with different value?
sorry if this post has been asked because i do not know what is the term to search for this type of question.
If you add $$
in first of string variable, you can define new variable.
<?php
$array1 = array("comp1", "comp2", "comp3");
foreach($array1 as $value) {
${"var" . $value} = "test $value variable";
}
echo $varcomp1; // outpu: "test comp1 variable"
echo $varcomp2; // outpu: "test comp2 variable"
echo $varcomp3; // outpu: "test comp3 variable"
?>
Example for define variable with string variable:
$string = 'hello';
$$string = 'new variable'; //define $hello variable
echo $hello; //Output: "new variable"
If I understand you properly you seem to be looking for Variable Variables:
$foo = 5;
$var = 'foo';
echo "{$var} => {$$var}";
would give you
foo => 5
You can do it with variable of variable
https://secure.php.net/manual/en/language.variables.variable.php