How to Receive Array Parameters via $_GET in PHP: Methods and Implementation Principles

Dec 04, 2025 · Programming · 9 views · 7.8

Keywords: PHP | $_GET array | URL parameter passing | bracket syntax | comma-separated

Abstract: This article provides an in-depth exploration of two primary methods for passing array data through URL parameters in PHP: using bracket syntax (e.g., id[]=1&id[]=2) and comma-separated strings (e.g., id=1,2,3). It analyzes the working mechanism of the $_GET superglobal variable, compares the advantages and disadvantages of both approaches, and offers complete code examples along with best practice recommendations. By examining the HTTP request processing flow, this paper helps developers understand how PHP converts URL parameters into array structures and how to choose appropriate methods for handling multi-value parameter passing in practical applications.

In web development, passing parameters through URLs is a common method for client-server interaction. PHP's $_GET superglobal variable is specifically designed to handle parameters passed via the GET method, but developers often encounter a question: how can multiple values be passed through a URL and processed as an array? This article will provide a technical analysis of this issue and present two practical solutions.

Bracket Syntax: Native PHP Array Parameter Passing

PHP offers native support for array parameter passing by appending square brackets [] to parameter names. When the URL format is foo.php?id[]=1&id[]=2&id[]=3, PHP automatically processes $_GET['id'] as an array containing three elements: [1, 2, 3].

The implementation of this method is based on PHP's parameter parsing mechanism. When PHP receives an HTTP request, it parses the query string, recognizes the [] pattern in parameter names, and constructs the corresponding array structure. The following code example demonstrates how to use this method in practice:

<?php
// Example URL: http://example.com/process.php?items[]=apple&items[]=banana&items[]=orange

if (isset($_GET['items']) && is_array($_GET['items'])) {
    echo "Received array contains " . count($_GET['items']) . " elements:<br>";
    
    foreach ($_GET['items'] as $index => $value) {
        echo "Element[" . $index . "]: " . htmlspecialchars($value) . "<br>";
    }
} else {
    echo "No array parameter received or parameter format is incorrect";
}
?>

The advantage of this approach is that it is fully supported natively by PHP, requiring no additional data processing code. However, its drawback is that URLs appear less concise, particularly when passing a large number of parameters, making the URL lengthy.

Comma-Separated Strings: A Concise Alternative

Another common method involves passing multiple values as a comma-separated string and then using the explode() function in PHP to convert it into an array. For example, with a URL format of foo.php?id=1,2,3, processing in PHP would be as follows:

<?php
// Example URL: http://example.com/process.php?ids=1,2,3,4,5

if (isset($_GET['ids'])) {
    $idArray = explode(",", $_GET['ids']);
    
    // Clean up possible whitespace
    $idArray = array_map('trim', $idArray);
    
    echo "Parsed array contains " . count($idArray) . " IDs:<br>";
    
    foreach ($idArray as $id) {
        if (is_numeric($id)) {
            echo "ID: " . htmlspecialchars($id) . "<br>";
        }
    }
}
?>

This method results in more concise URLs, especially suitable for passing large numbers of simple values. However, several considerations must be noted: first, values themselves cannot contain commas, as this would cause parsing errors; second, additional data validation and cleaning steps are required; finally, this method is not natively supported as an array format by PHP, necessitating explicit conversion code.

Technical Implementation Details and Comparison

From an underlying implementation perspective, when using bracket syntax, PHP creates an array structure while parsing the query string. The query string id[]=1&id[]=2 is parsed as:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
        )
)

In contrast, the comma-separated method produces simple string values that require manual processing by the developer. From a performance standpoint, both methods show minimal differences, but bracket syntax offers advantages in code simplicity and readability.

In practical applications, the choice between methods depends on specific requirements:

Security Considerations

Regardless of the method used, security must be considered when handling user-input URL parameters:

<?php
// Example of secure array parameter processing
function processGetArray($paramName) {
    if (!isset($_GET[$paramName])) {
        return [];
    }
    
    $values = $_GET[$paramName];
    
    // If it's a string (comma-separated case), convert to array
    if (is_string($values)) {
        $values = explode(",", $values);
    }
    
    // Ensure it's an array
    if (!is_array($values)) {
        $values = [$values];
    }
    
    // Filter and clean data
    $cleanValues = [];
    foreach ($values as $value) {
        // Perform appropriate cleaning based on actual needs
        $cleanValue = htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
        $cleanValues[] = $cleanValue;
    }
    
    return $cleanValues;
}

// Usage example
$ids = processGetArray('id');
?>

Additionally, validation of the number of array elements should be implemented to prevent denial-of-service attacks via excessive parameters.

Advanced Applications and Extensions

For more complex scenarios, consider the following extended methods:

  1. Multidimensional array passing: Use syntax like id[0][name]=value to pass multidimensional arrays.
  2. JSON encoding: Encode arrays as JSON strings for passing, then decode in PHP using json_decode().
  3. Custom delimiters: Choose more appropriate delimiters based on data characteristics, such as semicolons or vertical bars.

Below is an example using JSON encoding:

<?php
// Client-side JavaScript encoding array
// var params = {ids: [1, 2, 3, 4, 5]};
// var url = 'process.php?data=' + encodeURIComponent(JSON.stringify(params));

// PHP-side decoding
if (isset($_GET['data'])) {
    $data = json_decode($_GET['data'], true);
    
    if (json_last_error() === JSON_ERROR_NONE && isset($data['ids'])) {
        // Process $data['ids'] array
        foreach ($data['ids'] as $id) {
            echo "Processing ID: " . htmlspecialchars($id) . "<br>";
        }
    }
}
?>

This method is particularly suitable for passing complex data structures, but attention must be paid to URL length limitations and special character encoding issues.

Conclusion

In PHP, receiving array parameters via $_GET primarily involves two methods: native support through bracket syntax and manual parsing of comma-separated strings. Bracket syntax offers a more direct and PHP-idiomatic approach, while the comma-separated method provides advantages in URL conciseness. In practical development, the choice should be based on specific requirements, security considerations, and system constraints. Regardless of the method chosen, proper validation, filtering, and cleaning of user input are essential to ensure application security. As web applications grow in complexity, understanding these underlying mechanisms is crucial for building robust and secure PHP applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.