tags:

views:

63

answers:

2

For example:

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

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

+2  A: 

You could use next(), current(), prev(), end() set of fuctions. 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);
Jimmy Ruska
I have a function in a class which outputs an array. `$new_array = $class->returnsAnArray();`Results something like:`[0] = "Username"``[1] = "Group"`I would like to call that function, and then only output the value of key 1, all in the same line.For example, right now it would require:`$new_array = $class->returnsAnArray();``print $new_array[1];`But if there was a function that returns the specific key of an array, I could say all that with one line.`print array_output($class->returnsAnArray(), 1);`Is there something in PHP like array_output?
codemonkey613
There isn't, but you can make one if you use it often. function getValueIndex($output,$key){ return $output[$key]; } ... so then getValueIndex($class->returnsAnArray(),1);
Jimmy Ruska
Yep, that will work. Thanks
codemonkey613
+1  A: 

array_shift():

echo array_shift($fruits);

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

Felix Kling