Aller au contenu

Photo

off topic, but any answer appreciated


  • Veuillez vous connecter pour répondre
8 réponses à ce sujet

#1
TrekSL

TrekSL
  • Members
  • 32 messages
Our teacher gave us a days in month function in php, 99% of it i understand apart from the final element where he accesses the array. Due to a lack of info on this, could someone explain the last line of executed code to me - because it looks like we access the array according to the variable $month and then read -1 from that which makes bugger all sense to me!:

[/code][/code]function days_in_month($month=0,$year='')
{
if($month < 1 OR $month > 12)
    {
        Return 0;
    }
if(! is_numeric($year) OR strlen($year) !=4)
    {
         $year = date('Y');
    }
if($month == 2)
    {
    if($year %400 == 0 OR($year % 4 ==0 AND ($year % 100 !=0 ))
    {
        return 29;
    }
    }
$days_in_month=array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
return $days_in_month[$month - 1];
}

Modifié par TrekSL, 05 août 2011 - 02:44 .


#2
Roddish

Roddish
  • Members
  • 41 messages
i'm just guessing, but is it becuase most arrays start at position Zero rather than one, so instead of 1-12 months you have 0-11

#3
Lightfoot8

Lightfoot8
  • Members
  • 2 535 messages
Ok, I do not know the language(PHP) however I think I can answer this question for you.

Your Array
$days_in_month=array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

Arrays are 0 based indexed. that means you have an array with 12 elements in it that are indexed in the range of 0-11

so
$days_in_month(0) would = 31
and

$days_in_month(1) would = 28,

There is no index of 12 in your array. it has 12 elements indexed 0 throuth 11

Since your month numbers are in the range of 1 -12, you need to subtract one from the month number to have it line up with the array.

Hope that helps
L8

#4
Roddish

Roddish
  • Members
  • 41 messages
And the award for overzealous wordcount goes to Lightfoot8

:P

#5
Lightfoot8

Lightfoot8
  • Members
  • 2 535 messages
 Image IPB   I got an Award.    Cool.

Roddish wrote...

And the award for overzealous wordcount goes to Lightfoot8

:P



#6
Roddish

Roddish
  • Members
  • 41 messages
I wouldn't get too excited. You should see it, I made it out of my earwax and some bubble gum i found under my chair.

#7
CID-78

CID-78
  • Members
  • 1 124 messages
I can only confirm what been said. PHP is a bit easier since you only need to care if a variable is a single variable $ or array @. No need for types or memory size.

#8
TrekSL

TrekSL
  • Members
  • 32 messages
Crap! I forgot counting starts at 0. NOW that makes sense :) Lightfoot and Roddish to the rescue :)

#9
Roddish

Roddish
  • Members
  • 41 messages
crap!! does that mean i get an earwax award too?? knickers!!