Best way to use an array that is returned from a function immediately in PHP I have a function that returns an array and I want to check that a certain value is not set in the array.

function testFunction() {
    return array('key' =&gt; 404)
}

if (testFunction()['key'] &lt; 404) {
    // stay calm and carry on
}
else {
    // uh oh
}


I understand that the above will not work in php 5.3 (or anything below), however, I'd like to know what I should do in the above case. That is - what should I call the temporary array I create for the if statement? Or is there another way of dealing with this situation?

The following is what I would roughly do currently:

function testFunction() {
    return array('key' =&gt; 404)
}

$test_array = testFunction();

if ($test_array['key'] &lt; 404) {
    // stay calm and carry on
}
else {
    // uh oh
}


Is this an acceptable thing to do?
So, .. you want to simply check whether a certain key in an array is set to a certain value.

You can't do this directly on the function call because older PHP versions don't support array dereferencing. You are right when saying you'll need an intermediate variable.

The only question remaining is what to name it. Considering that the variable will probably be situated in a really small scope, don't worry about it too much. There is a saying which says, the bigger the scope, the bigger the name. You could just name it $list.

Old replies:


  Your code does something else as what
  you describe? If you want to see
  whether a given value is present in
  the array, use in_array().
  
  UPDATE:
  
  I believe I understand what you are
  trying to accomplish now. You just
  want to see whether the key is set?
  
  array_key_exists()
  
  PHP has got a pretty good online API,
  be sure to check it for existing
  implementations when looking for a
  solution.