Search code examples
phpvariablespostget

Using a variable key name to access $_GET / $_POST data in php


I need to use a variable as the key to access the $_GET data.
Is it possible?

This is my code:

 if($_GET){
   for($i=0;$i<9;$i++){
     echo $_GET["value0"];
     print_r(${'_GET["value'.$i.'"]'}); 
   } 
}

But it doesn't work.

I need to get $_GET['value0'], $_GET['value1'], and so on.


Solution

  • You should check the existence of each value with isset() before trying to access it. Also in php you don't need any complex string manipulations to put your variable in a string. You can just literally "put your variable in the string":

    for($i = 0; $i < 9; $i++) {
         if(isset($_GET["value$i"])) {
             echo $_GET["value$i"]; 
         }
       }