I would like to set a position in an array to equal the first $_GET
parameter that exists.
Here is the code I currently have which doesn't function exactly how I'd like as it uses arrays:
'searchOptions'=>array_merge(
isset($_GET['Search1']['searchoption']) ? $_GET['Search1']['searchoption'] : array(),
isset($_GET['Search2']['searchoption']) ? $_GET['Search2']['searchoption'] : array(),
isset($_GET['Search3']['searchoption']) ? $_GET['Search3']['searchoption'] : array(),
isset($_GET['Search4']['searchoption']) ? $_GET['Search4']['searchoption'] : array(),
isset($_GET['searchBar']['searchoption']) ? $_GET['searchBar']['searchoption'] : array(),
isset($_GET['searchOptions']) ? $_GET['searchOptions'] : array()
),
Is there a better way this can be done that avoids array_merge
and works properly? Currently right now it does not work if a string is passed in the $_GET
parameter as it needs to be an array.
The way this works is that only one of the $_GET
variables being checked will ever exist at one time, as such once there is one that isset the rest of them are irrelevant.
Is there a way to just do something similar to what I have but without treating it like I am merging arrays?
This could be broken up into many if statements that check and then set if it exists but it seems quite clunky.
In PHP >= 7.0 you can use the Null coalescing operator and chain them:
$options = $_GET['Search1']['searchoption'] ??
$_GET['Search2']['searchoption'] ??
$_GET['Search3']['searchoption'] ??
$_GET['Search4']['searchoption'] ??
$_GET['searchBar']['searchoption'] ??
$_GET['searchOptions'] ?? [];
If none are set then $options
is an empty array []
, if that's not what you want just replace it.