Lennart Bank
Lennart Bank

Reputation: 49

PHP use a _GET request string as a already written variable

I'm trying to make a one page website with many many different elements. These elements have to change each time you click somewhere. To do this I've made several arrays to loop through. Now I'm trying to do this with a _GET request. The moment I click on a link I will add "?page=key" to the url.

This string that I get in turn needs to be the name of the variable. To make things clear:

$homepage = array(
    [
        "href"          => "index.php?page=over",
        "title"         => "Over ons",
        "description"   => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua.",
        "img"           => "img/blue-block.png"
    ],

In the href you can see that I set the GET. Another array that I have is this:

$over = array(
    [
        "href"          => "index.php?page=medewerkers",
        "title"         => "Medewerkers",
        "description"   => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua.",
        "img"           => "img/blue-block.png"
    ],

Now the big question. How do I get the value "over" from the GET and use that value to speak to the already written variable $over so I can loop over this?

My initial thought was something like this, but this doesn't work:

    if(isset($_GET['page'])) {
        $page = '$' . $_GET['page'];
    }
    foreach($page as $block)
    {

Hope someone has a better idea! Thanks!

Upvotes: 1

Views: 114

Answers (1)

jszobody
jszobody

Reputation: 28911

Like this:

if(isset($_GET['page'])) {
    $page = ${$_GET['page']};
}

Now you can access $page['href'] for example.

Example: https://3v4l.org/uLYag


Of course, this doesn't validate $_GET['page'] and ensure it matches a predefined page array. Might be good to rethink your approach.

If it were me, I'd put all my page arrays together in one big array, so it's easier to validate. See here for a basic example: https://3v4l.org/0RJXX


For more info on "variable variables" see here:

PHP, $this->{$var} -- what does that mean?

Upvotes: 2

Related Questions