Question

Making a lookup on an array is simple:

$array = array(0 => 'Zero', 1 => 'One', 2 => 'Two');
$text = $array[2]; // $text = 'Two'

But if I don't want the intermediate $array variable, is there any built in way of making a lookup an array literal?

Examples

$text = array(0 => 'Zero', 1 => 'One', 2 => 'Two')[2]; // Syntax error
$text = array_value(2, array(0 => 'Zero', 1 => 'One', 2 => 'Two')); // Unknown command
Was it helpful?

Solution

As of PHP5.5 you can do:

$text = array(0 => 'Zero', 1 => 'One', 2 => 'Two')[2];

For versions lower than 5.5 you'll have to code a function like array_value() on your own as there is no built in function for it. Like this:

function array_value($key, $array) {
    if(!array_key_exists($key, $array)) {
        throw new Exception('Array has no index ' . $key);
    }

    return $array[$key];
}

OTHER TIPS

Another solution:

$array = array(0 => 'Zero', 1 => 'One', 2 => 'Two');
$pos = 2;

echo current(array_slice($array, $pos, 1));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top