Skip to content

Instantly share code, notes, and snippets.

@danybeltran
Last active October 12, 2024 04:30
Show Gist options
  • Save danybeltran/61a9cb27924890b16cdc341fe13d365c to your computer and use it in GitHub Desktop.
Save danybeltran/61a9cb27924890b16cdc341fe13d365c to your computer and use it in GitHub Desktop.
PHP search params
<?php
/**
* Gets the URL search params.
*
* @param string $url The URL to parse. If no URL is passed, `$_SERVER["REQUEST_URI"]` will be used instead
* @param bool $arrays If false, search params that are added at the end will overwrite any existing values
*/
function getQuery(string $url = "", bool $arrays = true)
{
$splittableUrl = $url === "" ? $_SERVER["REQUEST_URI"] : $url;
$split = explode("?", $splittableUrl);
/**
* Check if passed url has a text part before "?"
*/
$hasPath = count($split) > 1;
/**
* Get the search query
*/
$parseable = $hasPath ? $split[1] : $split[0];
/**
* This will store the query search key values
*/
$key_values = new ArrayObject();
/**
* Separates search params by "&"
*/
$withKeys = explode("&", $parseable);
foreach ($withKeys as $wKey) {
if (!$wKey) break;
/**
* Separates each search value by "="
*/
$kv = explode("=", $wKey);
/**
* Ignore keys where there is no corresponding value, eg when search is "a=1&b"
*/
if (count($kv) !== 2) break;
[$key, $value] = $kv;
/**
* Decodes the current search param
*/
$urlDecodedValue = urldecode($value);
if ($key_values->offsetExists($key) && $arrays) {
/**
* Checks if current value was already merged in an array
*/
$isCurrentValueArray = is_array($key_values->offsetGet($key));
$arrayValue = $isCurrentValueArray ?
/**
* If current value is already an array, merge existing array with new value
*/
array_merge($key_values->offsetGet($key), [$urlDecodedValue]) :
/**
* If not an array, create a new array value with existing and new value
*/
[$key_values->offsetGet($key), $urlDecodedValue];
/**
* Finally set array value
*/
$key_values->offsetSet($key, $arrayValue);
} else {
/**
* Sets single value
*/
$key_values->offsetSet($key, $urlDecodedValue);
}
}
return $key_values;
}
@danybeltran
Copy link
Author

Usage:

<?php
include "./utils.php";

$query = getQuery();

echo ($query["search"])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment