0

I am trying to print out PHP system arrays by looping through an array of the names of the arrays that I want to print. I am sure there is a simple way of escapeing the array names, but I can't seem too get it.
I have a long hard coded program that works, but I should be able to shorten it like the coding below.

 <?php
    $x = array("_GET","_POST","_REQUEST","_SESSION","_COOKIE");

foreach ($x as $value)
  {
  $xx = '$' . $value;
  echo $xx . '<br>';

    echo '<table border="2" style = "background-color:#d4d4d4">';
        foreach ($xx as $key=>$val )
        {
        echo '<br>value =';
            echo "<tr><td style= 'color:red;'>".$key."</td>";
            echo "    <td style= 'color:black;'>" .$val."</tr>";
        }
        echo"</table>";

        break;
  }
?>
2
Contributors
1
Reply
5
Views
4 Years
Discussion Span
Last Post by cereal
0

The first problem is $xx which is a string:

var_dump($xx); # output: string(5) "$_GET"

if you want to assign _GET as variable name then use $$ as:

$xx = '$' . $value;
var_dump(${$xx}); # output: Notice: Undefined variable: $_GET

but as seen, this is not enough, so change it to:

var_dump(${$value});

and by running /test.php?a=hello&b=world you will get what expected:

array(2) { ["a"]=> string(5) "hello" ["b"]=> string(5) "world" }

so at the end write:

$xx = ${$value};

Read these as reference:
* http://php.net/manual/en/language.variables.variable.php
* http://www.php.net/manual/en/language.variables.variable.php#81033

bye!

Edited by cereal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.