0

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

4
  • Play around a little with loops and the arrays you have got. You will certainly be able to figure that out yourself. Invest a little patience and you will actually learn how to use the language. Commented Sep 5, 2016 at 18:00
  • @arkascha i already spend a half day with no progressing that's why I'm asking Commented Sep 5, 2016 at 18:02
  • Sorry, but I don't really believe that, actually. Please show us a few of your attempts, a few of your tries. Thanks. Commented Sep 5, 2016 at 18:03
  • i used this print_r(${'product'}.$product) and other but it turn around the problem not fix it . i only need hoe to add $ to the variable to see it but i dont know how?? Commented Sep 5, 2016 at 18:05

2 Answers 2

2

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @tanaydin i see that while I'm searching the net but i didn't understand it . Now it much clear..
0
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

1 Comment

thanks for your help but for the code it just a example not the real code cause the real code is google analytics and it sooo much complicated that why i put it like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.