Search code examples
phparrayscoding-style

PHP: Access Array Value on the Fly


In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:

// the following results in an error:
echo array('a','b','c')[$key];

// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];

This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)


Solution

  • I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:

    $variable = array('a','b','c');
    echo $variable[$key];
    unset($variable);
    

    Or, you could write a small function:

    function indexonce(&$ar, $index) {
      return $ar[$index];
    }
    

    and call this with:

    $something = indexonce(array('a', 'b', 'c'), 2);
    

    The array should be destroyed automatically now.