|
Posted by Rik on 04/25/07 19:59
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!
Navigation:
[Reply to this message]
|