Jump to content

help understanding why we minus from the the argument being passed in


techin4

Recommended Posts

Hi,

I am a beginner with php and I am having a hard time understanding a section in my code.

The part I dont get is why we have to minus 1 from the number being passed into the array.

 

For example, $FaceNamePlural[$die1-1]

 

I tried looking at it over and over but I'm still very confused.

Can anyone help me on this...Thanks.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>
<?php

$FaceNameSingular = array("one", "two", "three", "four", "five", "six");
$FaceNamePlural = array("ones", "twos", "threes", "fours", "fives", "sixs");

function CheckForDoubles($die1, $die2)
{
    global $FaceNameSingular;
    global $FaceNamePlural;
    
    if($die1 == $die2) //  doubles
        echo "The roll was double ", 
            $FaceNamePlural[$die1-1], "<br />";
    if($die1 != $die2) //not doubles
        echo "The roll was a ", $FaceNameSingular[$die1-1], 
            " and a ", $FaceNameSingular[$die2-1], ".<br />";
            
}

function DisplayScoreText($Score)
{
    if($Score == 2)
        echo "you roll snake eyes! <br />";
        
    if($Score == 3)
        echo "you roll loose duece! <br />";
            
    if($Score == 5)
        echo "you roll fever five! <br />";
    
    if($Score == 7)
        echo "you roll natural! <br />";
        
    if($Score == 9)
        echo "you roll nina! <br />";
    
    if($Score == 11)
        echo "you roll yo! <br />";
        
    if($Score == 12)
        echo "you roll boxcars! <br />";                
}

$dice = array();
$dice[0] = rand(1,6);
$dice[1] = rand(1,6);
$Score = $dice[0] + $dice[1] ;
echo "<p>";
echo "The total score for the roll was $Score . <br />";

CheckForDoubles($dice[0],$dice[1]);
DisplayScoreText($Score);
echo "</p>";
?>
</body>
</html>

Hi, probably because the parameters $die are supposed to start counting from 1.

In php the arrays starts from 0, so the first element is [0 ], the second is [1] etc..

So if you pass the argument 2 meaning "the 2th element" you should do $array[2-1]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.