Current Location: Home> Latest Articles> Practical PHP Guide: How to Properly Handle and Manipulate URL Parameter Data Types

Practical PHP Guide: How to Properly Handle and Manipulate URL Parameter Data Types

M66 2025-07-09

Getting URL Parameters

In web development, URL parameters are a common way to pass data. PHP uses the global array $_GET to retrieve these parameters, where keys correspond to parameter names and values to their values. Here's an example:

// URL example: http://example.com/?name=John&age=25

$name = $_GET['name'];
$age = $_GET['age'];

echo "Name: " . $name . "<br>";
echo "Age: " . $age;

Output:

Name: John
Age: 25

Handling Integer URL Parameters

URL parameters are strings by default. When handling integers, it's recommended to convert them using intval() to avoid type errors. Example:

// URL example: http://example.com/?num1=10&num2=20

$num1 = intval($_GET['num1']);
$num2 = intval($_GET['num2']);

$result = $num1 + $num2;

echo "Result: " . $result;

Output:

Result: 30

Handling Float URL Parameters

When handling float parameters, use floatval() to convert strings to floats. Example:

// URL example: http://example.com/?num1=3.14&num2=2.5

$num1 = floatval($_GET['num1']);
$num2 = floatval($_GET['num2']);

$result = $num1 * $num2;

echo "Result: " . $result;

Output:

Result: 7.85

Handling Boolean URL Parameters

Boolean parameters can be converted using the filter_var() function with the FILTER_VALIDATE_BOOLEAN filter, supporting various representations such as true, false, 1, 0, etc. Example:

// URL example: http://example.com/?is_admin=true

$is_admin = filter_var($_GET['is_admin'], FILTER_VALIDATE_BOOLEAN);

if ($is_admin) {
    echo "You are an administrator";
} else {
    echo "You are not an administrator";
}

Output:

You are an administrator

Handling Array URL Parameters

Parameters with brackets (e.g., fruits[]) in the URL are automatically recognized by PHP as arrays. If parameters are passed as a comma-separated string, you can use explode() to convert them. Example:

// URL example: http://example.com/?fruits[]=apple&fruits[]=banana&fruits[]=orange

$fruits = $_GET['fruits'];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

Output:

apple
banana
orange

Summary

This article covered how to properly retrieve and handle various data types of URL parameters in PHP, including strings, integers, floats, booleans, and arrays. Mastering these techniques can enhance data interaction and user experience in web applications. In practice, proper type conversion helps avoid type errors and improves code robustness.