What are some best practices for adding elements to an array in PHP based on URL parameters?
When adding elements to an array in PHP based on URL parameters, it is important to properly sanitize and validate the input to prevent security vulnerabilities such as injection attacks. One way to achieve this is by using the filter_input() function to retrieve and sanitize the URL parameters before adding them to the array.
// Retrieve and sanitize URL parameters
$param1 = filter_input(INPUT_GET, 'param1', FILTER_SANITIZE_STRING);
$param2 = filter_input(INPUT_GET, 'param2', FILTER_SANITIZE_STRING);
// Initialize an array
$array = [];
// Add sanitized parameters to the array
if ($param1) {
$array[] = $param1;
}
if ($param2) {
$array[] = $param2;
}
// Print the array
print_r($array);