How to pass an array via $_GET in PHP?

By IncludeHelp Last updated : January 10, 2024

Problem statement

Given an array, write PHP code to pass the given array using the $_GET superglobal variable.

Passing an array via $_GET

To pass an array using $_GET super global, you have to encode the array first which will be done by the http_build_query() function. This method will generate a URL-encoded query string.

PHP code to create URL with URL-encoded query string

In this code, we are creating a query string and URL with the query string.

<?php
// Take an array
$student = ["name" => "Alex", "age" => 21, "city" => "New York"];
$query_string = http_build_query($student);
$url = "your_domain_name.com/script.php?" . $query_string;

echo "Generated encoded URL is: " . $url;
?>

Output

The output of the above code is:

Generated encoded URL is: your_domain_name.com/script.php?name=Alex&age=21&city=New+York

PHP code to access the array using the $_GET

Now, access the array using the $_GET superglobal variable.

$name = $_GET["name"];
$age = $_GET["age"];
$city = $_GET["city"];

To understand the above program, you should have the basic knowledge of the following PHP topics:

More PHP Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.