1

what in your opinion more standard / readable / efficient code of array declaration :

one way :

$days = array(1=>'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

then use : $days[$value]

or the second way :

$days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

then use : $days[$value-1]

update : i cant sure that the values be in [0-6] , because that i dont offer 3 way.

Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
  • 2
    I'd go with the zero-based (2nd) in order to comply directly with the internal PHP representation (e.g., `date('w')`). Also, note the ISO-8601 numeric representation (`N`). – jensgram Sep 13 '10 at 13:04
  • @jensgram: and what happens when the array has nothing to do with weekdays? ;) – fabrik Sep 13 '10 at 13:06
  • @fabrik and where this array keys do come from? – Your Common Sense Sep 13 '10 at 13:11
  • @Shrapnel: Nobody said we must stick with this example. At least OP didn't. – fabrik Sep 13 '10 at 13:19
  • @fabrik In general I would index my array corresponding to whatever I'm looking up. Thus, alternative 1 in general, which translates directly to alternative 2 when the data is (or ought to be) zero-based. **Also**, I'd judge by overall readability, not +/- 1 CPU cycle. – jensgram Sep 13 '10 at 13:25
  • @jensgram: I think that's the same that i said/asked. CPU cycle vs readability? I'm sure it doesn't comparable. – fabrik Sep 13 '10 at 13:28

3 Answers3

3

How about the 3rd way:

$days = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

and access it as:

$days[$value]

by ensuring that $value has value between [0,6]

codaddict
  • 445,704
  • 82
  • 492
  • 529
2

a funny one:

$days = array('Zer','Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');

(a friend of mine used a month name "Nulleary" once)
but seriously, it depends on where this array does come from.
For this particular example it should be just date("D",$tstamp);

though the whole problem negligible to me.
I am often using just

$days = explode(" ",'Sun Mon Tue Wed Thu Fri Sat');

and find it very handy.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
1

Definitely the first one (when keys are correctly defined).

In the second one you need to do a minus (extract) this is an unnecessary cpu cycle makes your code less readable and less maintenable.

Edit: I hope all of you lazy programmers are happy out there.

fabrik
  • 14,094
  • 8
  • 55
  • 71