Reputation: 15
I have multiple array variable in my page and i need to add them to google charts and make between 15 to 20 charts but for more easier i want to use a loop to print them All the variables have something in common in there names how to use one loop to print all variable
example: I have this variable :
$productshirts = ['red','green'];
$productpants = ['bleu','yellow'];
$productdress = ['green','gold'];
$products = ['shirts','pants','dress'];
now i need to print them in on code using loop foreach
foreach ($products as $product){
print_r('product'.$product);
}
but it not work. I get "productshurts , productpants , productdress" and not the array
so how to make them return the data in the array????
Thanks
Upvotes: 0
Views: 1288
Reputation: 395
foreach ($products as $product){
print_r(${'product'.$product});
}
it will print
Array
(
[0] => red
[1] => green
)
Array
(
[0] => bleu
[1] => yellow
)
Array
(
[0] => green
[1] => gold
)
On a note (and I don't know if you can change the stracture) it would be more readable (and easier to use and scale) to use a multi dimentional array
$product['shirts'] = ['red','green'];
$product['pants'] = ['bleu','yellow'];
etc
Upvotes: 0
Reputation: 5316
this is calling "Variable variables" http://php.net/manual/en/language.variables.variable.php here is your solution. Just change print loop to this code.
foreach ($products as $product){
$var = 'product'.$product;
print_r($$var);
}
It outputs
Array ( [0] => red [1] => green ) Array ( [0] => bleu [1] => yellow ) Array ( [0] => green [1] => gold )
Upvotes: 2