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.

6
  • 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). Commented Sep 13, 2010 at 13:04
  • @jensgram: and what happens when the array has nothing to do with weekdays? ;) Commented Sep 13, 2010 at 13:06
  • @fabrik and where this array keys do come from? Commented Sep 13, 2010 at 13:11
  • @Shrapnel: Nobody said we must stick with this example. At least OP didn't. Commented Sep 13, 2010 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. Commented Sep 13, 2010 at 13:25

3 Answers 3

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]

Sign up to request clarification or add additional context in comments.

2 Comments

This will apply only when we stick with this example.
i cant its came from db query that Not up to me
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.

2 Comments

@stereofrog: Thanks, that was funny. It's interesting how lazy programmers lives here.
@stereofrog whoops! yu're right. Gonna check my server right now - it must be burning of such overload! :)
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.

3 Comments

OH My Holy God! A whole CPU cycle! A disaster indeed.
Yeah and Achilles will never overtake Tortoise
Sorry, i'm definitely not a fan of dialogues like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.