PHP Code ..Needing all the help i can get

Hi, I am needing help with a dice code I am stuck on this assignment and cant seem to get past it…
I need to (1) Create two variables, $roll and $sum, both of which have a value of 0

(2) Create a while loop that will run 10 times. Keep track of what roll you’re on by increasing the $roll variable by 1 each time through the loop.

(3) Calculate a random number between 1 and 6.

(4) Print an image of the die cast based on the random number value. If the die images you saved above are in a folder called “dice” the statement in php looks something like

echo '<img src="dice/d1.jpg" width=10%>';]

to display a die with one dot.

(5) Add the value of the random number to $sum

(6) When the loop completes, you should create some space and a horizontal rule; then print the sum. Example results look something like:

You need to surround your code with backticks like so:

code here will appear formatted


This ia where I’m. at:

<!DOCTYPE html>


$roll = 0;
$sum = 0;

while($x * 10) {
echo "The sum of 10 rolls is: $x <br>";

$x = rand(1,6);

echo '<img src="dice/d1.jpg" width=10%>';
echo '<img src="dice/d2.jpg" width=10%>';
echo '<img src="dice/d3.jpg" width=10%>';
echo '<img src="dice/d4.jpg" width=10%>';
echo '<img src="dice/d5.jpg" width=10%>';
echo '<img src="dice/d6.jpg" width=10%>';
echo '<img src="dice/d7.jpg" width=10%>';
echo '<img src="dice/d8.jpg" width=10%>';
echo '<img src="dice/d9.jpg" width=10%>';
echo '<img src="dice/d10.jpg" width=10%><br>';

echo "The sum of 10 rolls is: $x";
echo array_sum($a);



better yet… instead of using those messy ‘backticks’

wrap your code in CODE TAGS

[ CODE ]

[ /CODE]

  • no spaces in the tags obviously…

Perhaps something like this then:

$roll = 0;
$sum = 0;

for($i=0; $i<10; $i++){
	//increment roll counter
	//generate random #
	$randomNum = rand(1,6);
	//display ranomd (dice) results
	echo '<img src="dice/d' . $randomNum . '.jpg" width=10%>';
	//update total (sum)
	$sum += $randomNum;

echo '<hr><br>TOTAL SUM: ' . $sum . '<br><br>';

1 Like

It looks like you’re struggling with the algorithm - the process your code takes to do what you want. You’ve got your required steps written out. Try adding them to your code as comments, that should help you see where you’re missing steps or where your code isn’t doing what you expect.

Another hint is to tackle one requirement at a time. For example, try writing some code that will show a different number on a dice each time it runs. Once you’ve solved that single problem you can think about how to integrate it with the rest of your work.


Thanks so much for the help!

Sponsor our Newsletter | Privacy Policy | Terms of Service