By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,348 Members | 1,397 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,348 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.

Apr 25 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Rik
Brian Kendig wrote:
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];
PHP != Perl, sadly, there's no way to do it like that.
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.
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!
Apr 25 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.