This question already has an answer here:
This is quite a stupid question. I want to find out how to increase a number in the end of the variable:
$Coffee1 = "black";
$Coffee2 = "brown";
$Coffee3 = "gray";
echo $Coffee1; => black
echo $Coffee1+1; => brown
echo $Coffee2+1; => gray
</div>
Here is how you can do that (code):
<?php
$Coffee1 = "black";
$Coffee2 = "brown";
$Coffee3 = "gray";
$varName = "Coffee";
for($varIdx = 1; $varIdx <= 3; $varIdx++) {
echo "
";
echo ${$varName . $varIdx};
}
Here is some explanation : Variable variables 1, 2
But better use arrays instead of variables in this case.
The mechanism you're looking for is an array.
http://php.net/manual/en/language.types.array.php
$coffee = [
"black",
"brown",
"gray"
];
$index = 0;
echo $coffee[$index]; // "black"
echo $coffee[$index+1]; // "brown"
echo $coffee[$index+2]; // "gray"
This is also where loops become handy.
foreach($coffee as $flavor) {
echo $flavor;
}
// "blackbrowngrey"