JokerMM JokerMM - 2 months ago 15
PHP Question

How to print multiple variables values using loop

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

Answer

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 )
Comments