0

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.

1
  • For reference: this isn't a 2D array. It's just an associative array you index with a dynamic key. PHP doesn't technically have 2D arrays, but a good-enough equivalent (in most cases) would be an array of arrays -- meaning in PHP's rendition of a 2D array, each of those values would itself be an array. Commented Jul 31, 2013 at 13:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

11 Comments

I am trying that, but even though it shows me the results I want, it's also showing this: Notice: Undefined index: $key, by the way I'm using PHP 5.5
@jfha73: Showing what?
check my previous comment, I just hit Enter by mistake, I just edited it.
@jfha73: That typically means you don't have a POST variable named 'key'. You'll want to make sure $_SERVER['REQUEST_METHOD'] === 'POST' and/or isset($_POST['key']) are true before you use $_POST['key']. Particularly if this code is in a script that handles both GET and POST requests.
@jfha73: Then there are probably quoting issues. Make sure you don't have $key in single quotes. $array['$key'] will not do what you want.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.