1

I think I'm doing something very, very wrong.....

I know I'm doing something incorrectly with rand($a,$b), but I've found it difficult to isolate as I'm transferring from C++ to PHP

Here's the relevant piece of source code:

<?php
                    $r = rand(1,7);
                    if ($r = 1){
                    echo '<p id="quote">a</p>';}
                    if ($r = 2){
                    echo '<p id="quote">b"</p>';}
                    if ($r = 3){
                    echo '<p id="quote">c</p>';}
                    if ($r = 4){
                    echo '<p id="quote">d</p>';}
                    if ($r = 5){
                    echo '<p id="quote">e</p>';}
                    if ($r = 6){
                    echo '<p id="quote">f</p>';}
                    if ($r = 7){
                    echo '<p id="quote">g</p>';}
                ?>
user1136646
  • 81
  • 1
  • 1
  • 6
  • 5
    You are doing something incorrectly with the equals signs. – Jon Jan 08 '12 at 02:41
  • 1
    use `mt_rand()` and `==` instead of `=`. The single `=` is the assigning operator, the double `==` is the comparison – Zoltan Toth Jan 08 '12 at 02:41
  • 2
    A way to avoid making these mistakes is to have the conditions switch places, so instead of `($car == "blue")`, you would say `("blue" == $car)`. This will cause the parser to complain if you make a typo and do `("blue" = $car)`, since you'd attempt to assign a value to a literal. This is often referred to as [Yoda conditions](http://stackoverflow.com/a/2430307/453331), since you're literally saying "if blue is car" instead of "if car is blue". – kba Jan 08 '12 at 03:20

3 Answers3

8

That entire block of code can be writtem much more simply as:

<?php
    $r = rand(0,6);
    echo '<p id="quote">'.chr(ord('a')+$r).'</p>';
?>

EDIT: By the way, what you were doing wrong is using = instead of == in your comparisons.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You are assigning the value of $r each time...

It should be:

<?php
                    $r = rand(1,7);
                    if ($r == 1){
                    echo '<p id="quote">a</p>';}
                    if ($r == 2){
                    echo '<p id="quote">b"</p>';}
                    if ($r == 3){
                    echo '<p id="quote">c</p>';}
                    if ($r == 4){
                    echo '<p id="quote">d</p>';}
                    if ($r == 5){
                    echo '<p id="quote">e</p>';}
                    if ($r == 6){
                    echo '<p id="quote">f</p>';}
                    if ($r == 7){
                    echo '<p id="quote">g</p>';}
                ?>
Jonathan
  • 5,495
  • 4
  • 38
  • 53
0
if ($r == 7)

allways double equal signs

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Alexander_F
  • 2,831
  • 3
  • 28
  • 61