I want to create a function (or method) that can fetch any key from $_GET array (or a $_POST or $_COOKIE array). The $_GET array can be flat, non-existing or multi-dimensional. The keys are associative and they may not always exist - as when an empty form is submitted -> no $_GET parameter is set in the url.
Here is a sample url for the scenario that I want to support: http://www.example.com/foo?foo[name]=John&foo[color][]=red&foo[color][]=green&foo[color][]=yellow&foo[gender]=male
.
The contents of this url shall be captured by the same get() function:
get($foo[name]) // Return value set in input field.
get($foo[color]) // Return array with none/one/many values (set in checkbox or multi-select, see sample code below).
// The functions shall be similar to:
$_GET['foo']['name'] // string
$_GET['foo']['color'] // array
The main use case in which I will be using the function is when a form is submitted, such as the one below. When the form is submitted, I want to fetch data from the checkboxes and radio buttons weather they are set or not.
<form method="GET">
<input type="text" name="foo[name]" value="">
<input type="radio" name="foo[gender]" value="male">
<input type="radio" name="foo[gender]" value="female">
</form>
Sample output for the form comes here.
Example 1: Form is posted with all fields set:
Array (
[foo] => Array (
[name] => John
[color] => Array (
[0] => red
[1] => green
[2] => yellow
)
[gender] => male
)
)
Example 2: Form is submitted as empty (so no keys exists, it is important that the function supports this scenario):
Array ()
Things I tried:
The first two scenarios with a flat or non-existing array are easy to manage, as shown in below function that will handle both flat and non-existing array keys. However, the function does not support multi-dimensional arrays (say, with up to two dimension levels).
// This will only work for a form that returns a flat $_GET array (e.g., http://www.example.com/foo?a=1&c=3).
// `get('foo[color]')` will not do the trick.
function get($key) {
if (isset($_GET[$key])) {
return $_GET[$key];
}
}
My question is how I can build a similar function that also supports a scenario with multi-dimensional arrays? How can I create the function so it will be valid for a multi-dimensional array?
Thanks.. :-)
PS: If your answer involves something like RecursiveArrayIterator(), I would appreciate a full example as this can be challenging to work with.
PPS: To reviewers who are quick on the dupe button: I am aware that StackOverflow has a ton of question regarding $_GET and arrays, and therefore encourage my reviewers to read and re-read the question before marking it as a duplicate. Again, the scenario here is how to create a function that supports getting a known key from a $_GET array, the $_GET array is multi-dimensional and it may or may not be set.