0

PHP | how to access a varaible dynmically?

Ok so , I have some variables say $product1 , $product2, $product3 ... and so on. Now, i want to access these variables using loops, but the thing is how can i attach the numbers , with the variable name (i.e product + 1 , product + 2), in order to access these variables, with any violation. Is there any specific operator there in php

21st Dec 2019, 12:47 PM
Saurav Kumar
Saurav Kumar - avatar
3 Respostas
+ 1
Try this <?php $product1 = "TV"; $product2 = "AC"; $product3 = "Flashlight"; $product4 = "Printer"; for($i = 1; $i <= 4; $i++) { $name = 'product' . $i; echo $i . ' ' . $name . '<br />'; } ?>
21st Dec 2019, 2:29 PM
Ipang
+ 1
Thank you . I also found another approach , which is quite similar, i.e by simply using ${'product'.$i}.
24th Dec 2019, 6:54 AM
Saurav Kumar
Saurav Kumar - avatar
0
You're welcome. I didn't even know that approach. Worth noting though 👍
24th Dec 2019, 8:25 AM
Ipang