Domanda

So I have the following code:

<ul>
<li>
<p>
<?php
$var = rand(1,2,3,4,5,6,7,8,9,10);
if ($var == 1){
print '<a href="/dir1/file1">link1</a>';
}
if ($var == 2){
print '<a href="/dir2/file2">link2</a>';
}
if ($var == 3){
print '<a href="/dir3/file3">link3</a>';
}
if ($var == 4){
print '<a href="/dir4/file4">link4</a>';
}
if ($var == 5){
print '<a href="/dir5/file5">link5</a>';
}
if ($var == 6){
print '<a href="/dir6/file6">link6</a>';
}
if ($var == 7){
print '<a href="/dir7/file7">link7</a>';
}
if ($var == 8){
print '<a href="/dir8/file8">link8</a>';
}
if ($var == 9){
print '<a href="/dir9/file9">link9</a>';
}
if ($var == 10){
print '<a href="/dir10/file10">link10</a>';
}
?>
</p>
</li>
</ul>

But it outputs this error:

"Warning: rand() expects exactly 2 parameters, 10 given..."

So I wonder how could I random the values of this variable and then print() only on in the p tag?

È stato utile?

Soluzione

Since your numbers are in sequence, you could simply do

$var = rand(1,10);   // that will work on range 1 - 10


Function Prototype:

int rand ( int $min , int $max )

Altri suggerimenti

The problem is not with how many arguments you can pass to a function, but what arguments that function expects.

rand takes 2 arguments - a minimum value and a maximum value. It doesn't take an unspecified number of arguments that it picks from.

You just want:

rand(1, 10)

You don't need a condition here...

<ul>
    <li>
        <p>
          <?php printf('<a href="/dir%d/file%d">link%d</a>', rand(1,10)); ?>
        </p>
    </li>
</ul>

will do..

will do..

The mistake you were doing is.. rand() expects two parameters.. the minimum number and the maximum number.

Sidenote : If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax()

$var = rand(1,10);

it means rand from 1 to 10

Rand a number between low limit and upper limit rand(0,10). If you have a list of numbers like [1,14,1663,1773] and you want to get a random number from these one, use the random function to get a number between 0 and count(array) - and than print the element at that index.

Since the error message is clear.

rand() function expects exactly two parameters.

If you want to generate a random number between 1 and 10, write this:

rand('1', '10')

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top