views:

48

answers:

3

I was just wondering how I can get the content of a variable starting from the last value instead of the first ( using foreach),

 $variable = [1,2,3,4];

how can I print 4 then 3 and so on (if the size of the variable in unknown, is it possible to get the last value first).

thanks

+5  A: 
$last = array_shift(array_reverse($array, TRUE));

Or simply by

foreach (array_reverse($array) as $element) { ... }
Alex
Thanks for your help.
amir
Or the single function approach array_pop()
Mike B
Yes it's quicker to obtain the last one really
Alex
+2  A: 

you can use array_reverse(). Some examples:

foreach (array_reverse($variable) as $num) {
    echo $num;
}

implode(',', array_reverse($variable));
soulmerge
A: 

end() also works.

Alix Axel