Re: Array mysteries
| From: | Larry Garfield | Date: | Sun, 11 Mar 2007 18:42:46 +0000 |
| Subject: | Re: Array mysteries | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-250244@lists.php.net to get a copy of this message | ||
On Sunday 11 March 2007 12:02 pm, Edward Vermillion wrote:
> >> At 10:05 AM +0100 3/11/07, Tijnema ! wrote:
> >>> - You could define $wdays inside the function
> >>> function convert_from_weekday ($weekday) {
> >>> $wdays = array
> >>> (0 => "Sonntag"
> >>> ,1 => "Montag"
> >>> ,2 => "Dienstag"
> >>> ,3 => "Mittwoch"
> >>> ,4 => "Donnerstag"
> >>> ,5 => "Freitag"
> >>> ,6 => "Samstag"
> >>> );
> >>> return $wdays[$weekday];
> >>> }
> >>> $day = convert_from_weekday(0) // $day = "Sonntag"
*snip*
> > It's the technique and not the specific data thing I was
> > addressing. When I'm confronted with a case condition, I typically
> > use the switch statement. But, your solution provided me with
> > another way to look at that.
> >
> > Cheers,
> >
> > tedd
>
> But what's the cost of this in a loop, rebuilding the array each
> time, as compared to a switch statement? Just another thought...
>
> Ed
That's why you can just declare it static:
function convert_from_weekday ($weekday) {
static $wdays = array(
0 => "Sonntag",
1 => "Montag",
2 => "Dienstag",
3 => "Mittwoch",
4 => "Donnerstag",
5 => "Freitag",
6 => "Samstag"
);
return $wdays[$weekday];
}
And then it's only ever defined once, and the lookup is just an array-key
search that happens down in the engine. I do this sort of mapping all the
time.
--
Larry Garfield AIM: LOLG42
larry@garfieldtech.com ICQ: 6817012
"If nature has made any one thing less susceptible than all others of
exclusive property, it is the action of the thinking power called an idea,
which an individual may exclusively possess as long as he keeps it to
himself; but the moment it is divulged, it forces itself into the possession
of every one, and the receiver cannot dispossess himself of it." -- Thomas
Jefferson