$_GET

This YouTube video was created by Steve Griffith.

The $_GET variable is an associative array of variables passed to the current script via the URL parameters or query string.

<?php 
  // 
  echo 'Hello, '.$_GET['name']; 
?>

Assuming the URL https://example.com?name=World, the above example will output something similar to:

Hello, World

Dynamic Template with $_GET

Now, that we know how to pass and receive variables through the URL, we can use this feature to create dynamic templates and entire sites. For example, lets say we wanted to make a very basic blog, and we stored all of the data for the posts in the PHP array.

$posts = [
  'post-1': [
      'title' => 'My First Post',
      'text' => 'Fugiat exercitation eiusmod cillum aliqua.'
  ],
  'post-2': [
      'title' => 'My Second Post',
      'text' => 'Fugiat exercitation eiusmod cillum aliqua.'
  ]
];

With this array and a small conditional statement, we can display the different posts based on the value past throught the URL.

<?php 
  $posts = [
    'post-1': [
        'title' => 'My First Post',
        'body' => 'Fugiat exercitation eiusmod cillum aliqua.'
    ],
    'post-2': [
        'title' => 'My Second Post',
        'body' => 'Fugiat exercitation eiusmod cillum aliqua.'
    ]
  ];

  // checks if slug variable was passed through the url
  // and if the value of slug is a key in the $posts array
  if (isset($_GET['slug'] && isset($posts[$_GET['slug']]))) {
    $post = $posts[$_GET['slug']];
  } else {
    // fall back
    $post = $post['post-1'];
  }
?>
<!DOCTYPE html>
<html lang="en">
<body>
  <h1><?php echo $post['title']; ?></h1>
  <p><?php echo $post['body']; ?></p>
</body>
</html>