<?php
if (isset($_POST['Roll!'])) {
$sides = $_POST['sides'];
$rolled = rand(1,$sides);
echo "$rolled was rolled by the dice, it is now out!";
}
?>
This is the code I currently have. After rolling that number, however, I want it to roll again, but without the previously rolled number, until it has rolled all number except one, which would be the winning number. I have no idea how to go about doing that. Any ideas?
EDIT: I'm sorry, I should have been more clear, thank you all for the help so far, but I also need to echo each number rolled, such as
echo "$rolledArray[0] was rolled, it lost.\n";
echo "$rolledArray[1] was rolled, it lost.\n";
echo "$rolledArray[2] was rolled, it lost.\n";
echo "$rolledArray[3] was rolled, it lost.\n";
echo "$rolledArray[x] was rolled, it lost.\n";
echo "$rolledArray[x] was rolled, it lost.\n";
echo "$rolledArray[50?] was rolled, it lost.";
EDIT AGAIN: Also I only want them to have to click Roll! once, not multiple times until they've rolled all the numbers, meaning no need for session, I think, though I could be wrong, most of you are clearly more experienced than me.
Sorry, I should have mentioned that before as well.
To answer your direct question:
You can put all of the possible numbers into an array, and get a random index for that array. Once you have an index, remove the item from the array and redo the random over the smaller array:
$possible = range(1, $_POST['sides']); // build the possible values
$rolledIndex = rand (0, count($possible)); // get a random index
$rolled = $possible[$rolledIndex]; // get the rolled number
unset($possible[$rolledIndex]); // and remove the rolled nuber
// now you can simply redo the random:
$rolledIndex = rand (0, count($possible)); // get a random index on the smaller array
$rolled = $possible[$rolledIndex]; // get the 2nd rolled number
However, If you want to have a random order on the dice throws, simply use this:
// generate an array with all values from 1 to the posted value (e.g. 1,2,3,4,5,6)
$possible = range(1, $_POST['sides']);
// this reorders the array by random (e.g. 4,3,1,5,2,6)
$throwOrder = $possible;
shuffle($throwOrder);
print_r($throwOrder);
Now you can simply iterate over the $throwOrder array and have a random order of dice throws:
Array (
0 => 4,
1 => 3,
2 => 1,
3 => 5,
4 => 2,
5 => 6
)
Edit To get the desired output from the second method, simply do this:
// get the last index of the array of thrown dices
$lastIndex = count($throwOrder)-1;
// iterate through the array, printing the results
foreach ($throwOrder as $key => $rolled) {
// check if the current key matches the last key in the array
if ($key != $lastIndex) {
// if not, the number has lost
echo $rolled, " was rolled, it lost.\n";
} else {
// we have reached the last element of the array
echo $rolled, " was the last, it won.\n";
}
}
I think you need to have array $thrownNumbers, which holds every number previously thrown. And every new throw (OMG... the word), you check if it's in array. If yes, throw again. Simplest possible solution.
Edit: As for keeping the array during moving to another page, you can use:
$_SESSION
cookies (hm)
have serialized array as hidden value in form
There.
You can throw it in the $_SESSION to keep track of it between posts/request or append it to the URL and pass it yourself each time as a URI param.
<?php
if(!isset($_SESSION['numbers']){
$_SESSION['numbers'] = range(1,6); //same as array(1,2,3,4,5,6)
}
$numbers = $_SESSION['numbers'];
if(count($numbers)>1){ //is more than one number left
$rand_index = array_rand($numbers); //choose a number from an array, returns the index
print('you rolled '.$numbers[$rand_index].' loser'); // tell them they lost
unset($numbers[$rand_index]); //remove that element from the array
$_SESSION['numbers'] = $numbers; //set new array back to session
}else{
print(array_pop($numbers).' is the winner!'); //pop the remaining number out of the array and print it with winner notification
}
?>
edit: updated to session usage
It is not a bad idea to add to the URL if you use properly. The good side is that you don't store data in the session, the bad side is that the request is bigger each time. To avoid tampering you can use:
$url = 'numbers.php?throwed='.implode(',',$throwed).'&sign='.sha1(serialize($throwed).'mysecretpassword');
And use this to get check:
$throwed = explode(',',$_GET['throwed']);
$not_tampered = sha1(serialize($throwed).'mysecretpassword') == $_GET['sign'];
Just create an array (or other type of list) of all possible numbers and randomly order it. Then, instead of picking a new number each time just advance through the array until you get to the last but one.
Alternatively, you could just go straight to the last number in the list and that's the winner.
It depends on the situation, but creating an array with all the possible numbers for all the visitors in your web can be a very bad idea, sessions files can grow unnecessarily.
If they are like numbers from 1 to 10 I think it would be OK, but if they are numbers from 1 to 1 million creating arrays with those ranges saved in the session is pretty much a bad idea.
I think it's better to save the rolled results and generate a new one until it doesn't exist in the array.
Related
i want to display in my system just one record with the same id.
for example: 01,01,02,02,03,03.
I just want to display 01,02,03.
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
$number = "01,01,02,02,03,03";
$result = implode(',',array_unique(explode(',', $number )));
echo $result; // output 01,02,03
Happy Programming
I'm trying to create a function to fetch one or more random entries from my array but I'm having an "illegal call" array_rand error on my flow.
Then I realized that not all PHP functions are supported through GlobiFlow, so I was hoping that there's a workaround for this one.
screenshot:
Here are my variables:
choicesval = my array
randum = random number from 1 - 7
xField = random item(s) that were chosen from my array_rand
Here's the furthest that I got:
explode(",", choicesval)[intval(randum)]
But the problem is, it returns the element from my array based on the index. For example, my randnum got a value of 3, so in my Xfield, it will return the element at index 3 and not select 3 random items from my array.
Hope I'm making any sense at all.
I'm not successful in correcting my error above, however, I've found a workaround to achieve the same result.
I created a new var named limitnum = 0, then a for each loop:
for each item:
if limitnum <= randnum
choicesval = [(Ref Client) Company Name]. ", " .[(Variable) choicesval]
limitnum += 1;
end if
continue()
I have two arrays. One array $People currently creates number of 44 individuals. Lets just assume currently its
$People = array('1','2',...,'44');.
I have another array of 15 elements.
$Test = array('A','B',...'O');
Now I want to be able to assign the test randomly to each individual. I know how to do this using random function in php.
Where it has got tricky for me and what I need help with is how can I even out the test array. What I mean by this is since there are currently 44 individuals (this array will grow in future), what I want is 14 test versions to have 3 individuals and 1 version would have 2. So I want the test array to even out. I also want it to handle as growth of $People array.
Ex: Test Version D will have individual '4', '25'. Every other version has three random individuals.
Few ideas I came up with are things like running random integer on $Test array and which ever gets highest/lowest gets 2 individuals and rest three. This would give a problem when I increase the size of $People array; to deal with that I though about using modulus to figure out what will be even number of $Test beforehand.
I can do this and other ideas but am pretty sure there has to be a better way to do this.
Clarifying your situation:
You want to distribute the values inside $People randomly amongst your $Test array. The problem you stated you are having is that the amount of values in $People isn't always perfectly dividable by the amount of values in $Test, and you aren't sure how to go about implementing code to distribute the values evenly.
Proposed solution:
You could obtain the values in a foreach loop randomly 1 by 1 from a shuffled version of $People and put them in a new array called $Result. You would also have a conditional checking if you have extracted all the values from the shuffled $People array: if($count>=$arrayCount) where $arrayCount=$count($shuffledPeople);. If you have obtained all the values, you first make the $bool value false (in order not to iterate through the while loop anymore, and then you break; out of the foreach loop.
$Result =[];//the array containing the results
$shuffledPeople = $People;
shuffle($shuffledPeople);//mixing up the array
$arrayCount = count($shuffledPeople);//finding the total amount of people
$count = 0;
$bool = TRUE;
while ($bool)
{
foreach($Test as $value)
{
$Result[$value][] = $shuffledPeople[$count];
$count++;
if ($count>=$arrayCount)
{
$bool = FALSE;
break;
}
}
}
To view the results, all you would need to do is:
foreach ($Result as $key => $value)
{
echo "{$key}: <br>";
if (is_array($value))
{
foreach ($value as $something)
{
echo "-->{$something}<br>";
}
}
else
{
echo "-->{$value}<br>";
}
}
I believe that this is what you want to do...
Assume that you have $people and $test arrays. You want to know how many people per test...
$ppt = ceil(sizeof($people)/sizeof($test));
Now, $ppt is the people per test. The next step is to shuffle up the people so they are randomly assigned to the tests.
shuffle($people);
Now, we can chunk up the people into sub-arrays such that each sub-array is assigned to a test. Remember, the chunks are random now because we shuffled.
$chunks = array_chunk($people, $ppt);
Now, everyone in $chunks[0] will take $test[0]. Everyone in $chunks[1] will take $test[1]. Everyone in $chunks[2] will take $test[2].
Trying to get this code to work. It might be easier to show what I'm trying to do, and what is missing:
<?php
$array=array(
"something",
"something else"
);
/*pick a random entry in the array and store it as $output*/;
if(strpos($output,"else") !== false){
//do stuff;
}
echo "<div>";
echo $output
echo "</div>"
?>
As you can see, I'm having trouble trying to store a random entry in $output. What I want to do is to pick a random entry from the array, run a strpos on the result to do additional things if the conditions are met, and then output the same random entry between the divs.
EDIT: In case it's not clear, the line commented with /* and */ is supposed to be a 'fill in the blank' line, and not a 'this comment refers to the lines of code below' comment.
Use array_rand() to get a random entry.
$output = $array[array_rand($array)];
Generate a random number between zero and one less than the length of the array, use that as the array index to get a random item from the array.
<?php
$output = $array[rand(0, count($array)-1];
I have this code:
$fookerdos = '';
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos .= file_get_contents($someposoA);
//to print them i you want
print $fookerdos;
So my problem that for this code will outputs many numbers becouse of many files.
for example will out output this
3.5 -6.7 6.68 -0.2 and so on..
now i want all this numbers to make them (addition)
i know how to addition some 2-3 variables, but i additions many numbers that I even dont know how many they are.
for example
print "3.5 + "-6.7" "6.68" "-0.2";
Thx :)
Does each file contain only a single number, or can they have more than one numbers?
From your previous edits, it seems as if one file contain only a number.
In that case, you can store the values in an array and sum the numbers using array_sum() or perform any other calculation as needed.
Here is a sample code for you:
$fookerdos = array ();
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos[] = file_get_contents($somekerdos);
}
echo array_sum ($fookerdos);