简体   繁体   中英

Having problems with php rand function

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>';}
                ?>

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.

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>';}
                ?>
if ($r == 7)

总是两个等号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM