I have this array:
$array = array (
"key1" => "Value 1",
"key2" => "Value 2",
"key3" => "Value 3",
"key4" => "Value 4",
...
);
I am submitting a key with a form, so I want to assign a variable the value that belongs to that key, for example:
$key = $_POST['key'];
$value = ?????; //this is what I need
This might be very simple, but I haven't done it in a very long time and I have forgotten how to do it.
Thanks.
This should do the trick:
$value = $array[$key];
or without another variable:
$value = $array[$_POST['key']];
If you do receive a Notice: Undefined index ...
you should check your array before you try to get the value with:
$value = array_key_exists($_POST['key'], $array) ? $array[$_POST['key']] : null;
This condition checks if the key exists. If so, it gets the value. If not, the value of $value
will be null
.