Using $_GET variable to determine which index in an array to reference
I am getting data via $_GET['value']
and I want that value to represent a variable of an array.
I'm building a sort by drop-down menu with 3 options.
I want to search an array for a match.
So if the $_GET['value'] == 'name'
then I want to search my array for 'name'
and use that value as the data sent to my query.
Sort By:
<开发者_StackOverflow;select name='1' value='name'>Name</select>
<select name='1' value='manufacturer'>Brand</select>
So when php gets the values of the select menu I want to do an array search for that name and use its value to represent a variable to be sent to my query.
Determine if the value received in $_GET
is in your array, then retrieve it by the index.
// Your values are stored in this array
$your_array = array("name" => "some name", "place" => "some place");
// Check if the `value` is a key in your array
if (array_key_exists($_GET['value'], $your_array)) {
$search_value = $your_array[$_GET['value']];
}
else {
// Not found.. Use some default value instead.
}
You can check if the value is in the array by using in_array() method
Example:
$yourArray = array(...);
if ($_GET['value'] == 'name') {
if (in_array($theName,$yourArray)) {
// build your query
}
}
if (isset($_GET['value'])) {
if ($value = $your_array[$_GET['value']]) {
//do something by this $value
}
}
else {
echo 'nothing';
}
精彩评论