codemonkey613
codemonkey613

Reputation: 998

Array - How do I access value at specified key, without using $array['key'] method?

For example:

$fruits = array(
    1 => 'apples',
    2 => 'lemons',
    3 => 'bananas'
);

Is there a function to output lemons, without using $fruits[2]?

Upvotes: 2

Views: 168

Answers (2)

Jimmy Ruska
Jimmy Ruska

Reputation: 468

You could use next(), current(), prev(), end() set of functions. You could use a foreach on the array. You could use the list($var,$var1,$var2...) = $arr construct. Be more specific as to what you're trying to do.

EDIT:

If you're looking for a way to echo it in text use 
$foo='LEMON: '.$fruits[2].' =)';
OR
$foo=:LEMON: {$fruits[2]} =)";

foreach($fruits as $k => $v) if ($k===2) echo $v;

list($f1,$f2,$f3) = $fruits;
echo $f2;

next($fruits);
echo next($fruits);

array_shift($fruits);
echo $array_shift($fruits);

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816422

array_shift():

echo array_shift($fruits);

But it works only with the first element in the array of course ;)

Upvotes: 1

Related Questions