How do I do something like $color = ("red", "yellow", "blue")[$colornum]?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
How do I take an index of a literal array, instead of a variable?

That is, say I want to get the short name of a month. Can I do
something like:

$monthname = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec")[$month];

or do I always have to do:

$blah = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec");
$monthname = $blah[$month];

It seems a shame to have to create a variable specifically for this
one-shot purpose.

Re: How do I do something like $color = ("red", "yellow", "blue")[$colornum]?

Brian Kendig wrote:
Quoted text here. Click to load it

PHP != Perl, sadly, there's no way to do it like that.

Quoted text here. Click to load it
Quoted text here. Click to load it

Well, in this particular case one would offcourse use some date  
function, makes more sense and makes use of your locales.

There is no real win either your way. The array still has to be created  
in memory, it's just anonymous and will be removed as soon as PHP is  
done with it. If you're worried about memory consumption you can always  
unset() them afterwards offcourse.

If you're desparate to do it with a single oneliner just use:

function valueAt($array,$at){
    return (is_array($array) && isset($array[$at])) ? $array[$at] : null;

$blah = valueAt(array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",  
"Aug", "Sep", "Oct", "Nov", "Dec"),$month);

PHP, it seems more wordy, but I actually like the legibility that comes  
from it a lot. Digging through perl codes can often be very,very confusing.
Rik Wasmus

Estimated date being able to walk again: 01-05-2007.
Less then a week, hurray!

Site Timeline