PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I want to be able to create a set of random values, and increment one specific variable if the random number equals, 1, 2, 3... or some othe value I chose.
How should I program this? What am I doing wrong?
What I want to do is simulate a random election, by creating av random variable k. If this contains a certain number (eg 1) I want party A to get one more wote and. If this contains for example the value 3, I want party D to get one more vote, and so on...
I've made a few changes below to get it to work:
1) You need to set the "add one" expression inside curly brackets; this makes it part of the if() function.
2) You were echoing the variable $Ap for some reason; you just need to echo the variable $A.
<?php
$k = rand(1,10);
$A = 0;
for ($i = 1; $i<=1000000;$i++)
{
if ($k==1)
{
$A= $A + 1; // This you did not set inside parentheses (curly brackets)
}
}
echo $A; // This you set as $Ap for some reason
?>
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Thanks, but the code only prints 0 Which is the value set for A before the foor loop. Why?
Thanks
Because the rand() only runs once before the loop so $A will always be either 0 if the rand() is not 1 or 1000000 if rand() returned 1. Move the rand() inside the loop, but you'll probably have better luck with the code I posted.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Thanks, but the code only prints 0 Which is the value set for A before the foor loop. Why?
Thanks
Because the rand() only runs once before the loop so $A will always be either 0 if the rand() is not 1 or 1000000 if rand() returned 1. Move the rand() inside the loop, but you'll probably have better luck with the code I posted.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
At the start of the loop (inside) you need a <tr> and at the end (inside) you need a </tr> so that each iteration is a new row.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.