0

I have an array, anArray, that I loop through, like so:

foreach ($anArray as $key) {

    echo $_GET[$key];

}

I get numerous errors saying:

Undefined index: $key

Which is true, but I don't know how to get my PHP to recognise $key is a variable, and not just a string.

If I print out the list of the $_GET $key => $value pairs, and a list of $anArray, they both contain at least some of the same values.

Can anyone tell me where I'm going wrong?

Many thanks.

2
  • This should work as is. $arr[$var] is supported perfectly fine. Commented Mar 25, 2014 at 16:22
  • I'm not trying to get the value from the array, I'm trying to get the value from the $_GET query, when the index is equal to a value in the array. Commented Mar 25, 2014 at 16:24

2 Answers 2

1

It already does recognize $key as a var, your syntax is correct, you can eliminate the error this way:

Check if $_GET array has $key in it first like this:

if array_key_exists($key, $_GET) {
    echo $_GET[$key];
}
Sign up to request clarification or add additional context in comments.

Comments

0

The error is telling you that you have values in $anArray that do not exist as indexes in $_GET.

For instance,

http://someserver/somepage.php?var1=this&var2=that

Will result in a $_GET like:

array(
  'var1' => 'this',
  'var2' => 'that'
)

So, if $anArray is like:

array('var1','var2','var3');

Your loop will work fine for var1 and var2, but when it gets to var3 it will issue the undefined index error.

If you can't know whether all the elements in $anArray are going to exist in $_GET, and you just wish to suppress the error notice, the usual approach is to wrap your execution block in an isset(); wrapper:

foreach ($anArray as $key) {
  if (isset($_GET[$key])) {
    echo $_GET[$key];
  }
}

Or use array_key_exists() as suggested by @HappyMary.

Comments

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.