standard / readable array declaration and using
-
02-10-2019 - |
Question
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.
Solution
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.
OTHER TIPS
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]
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.