I currently have a piece of code that is selecting random values from an array but I would like to prevent it from selecting duplicate values. How can I achieve this? This is my code so far:
$facilities = array("Blu-ray DVD Player","Chalk board","Computer", "Projector",
"Dual data projector", "DVD/Video");
for($j = 0; $j < rand(1, 3); $j++)
{
$fac = print $facilities[array_rand($facilities, 1)] . '<br>';
}
I think you should look at array_rand
$facilities = array("Blu-ray DVD Player","Chalk board","Computer","Data projector","Dual data projector","DVD/Video");
$rand = array_rand($facilities, 2);
^----- Number of values you want
foreach ( $rand as $key ) {
print($facilities[$key] . "<br />");
}
You can return multiple random keys from array_rand() by specifying the number to return as the second parameter.
$keys = (array) array_rand($facilities, rand(1, 3));
shuffle($keys); // array_rand() returns keys unshuffled as of 5.2.10
foreach ($keys as $key) {
echo $facilities[$key] . '<br>';
}
Related
I want to build a combination of numbers and letters separated by - (minus sign). i.e 1-R-3. The first number are in an array called $Points ,the letters are stored in a array called $Color and the last number is in a third array called $Points2;
$Points = [1,2,3,4];
$Color = [R,B,V,Y];
$Points = [1,2,3,4];
I want the result to be one one row 1-R-1, 2-B-2 and so on. Now the result outputs as:
1
(minus sign)
R
(minus sign)
3
`
$Bind = "-";
$foo = $Points[0] . $Bind . $Points[1];
I have tried to convert the integer to a string by (String) but have not worked.
Can somebody help me to get the result on one line? I bet i'm missing something easy!
EDIT: The format in the arrays where incorrect since I forgot ->plaintext when doing my web-scraping.
/U
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
foreach ($Points as $point=>$value) {
echo $value . '-' . $Color[$point] . '-' . $value . PHP_EOL;
}
Note that the values in the $Color array need to be in quotes to avoid errors.
You have two arrays called $Points, so I've renamed one.
This just combines the three arrays by using foreach and using the key of each element and using it to access the other arrays at the same index...
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points1 = [1,2,3,4];
$bind = "-";
foreach ( $Points as $key => $val ) {
echo $val.$bind.$Color[$key].$bind.$Points1[$key].PHP_EOL;
}
This may be occurring because of the tabs or carriage return:
<?php
$points = [1,2,3,4];
$colors = ['R','B','V','Y'];
$bind = '-';
$foo = [];
for ($x = 0; $x <= 3; $x++) {
$foo[$x] = $points[$x].$bind.$colors[$x].$bind.$points[$x];
}
foreach($foo as $value) {
echo $value.'<br>';
}
?>
Result:
1-R-1
2-B-2
3-V-3
4-Y-4
You can use php join function. For example:
$results = [];
for ($i = 0; $i < count($Points); $i++) {
$results[] = join('-', [$Points[$i], $Colors[$i], $Points2[$i]]);
}
// Now you have your combined values in $results array
var_export($results);
You can combine array into one string like
<?php
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points = [1,2,3,4];
$result='';
$bind='-';
foreach ($Points as $index => $value) {
$result .= $value .$bind . $Color[$index] . $bind . $value.PHP_EOL;
}
echo $result;
?>
DEMO
I am using this table to generate password. I am using this code to shuffle and it shuffles only rows and not columns randomly. I want to place them randomly in tables mixing both rows and column values.
$matrix=array();
$matrix[3][0]="h5";$matrix[3][1]="h3";$matrix[3][2]="96";$matrix[3][3]="45";$matrix[3][4]="oo";
$matrix[1][0]="39";$matrix[1][1]="k4";$matrix[1][2]="i2";$matrix[1][3]="j9";$matrix[1][4]="g5";
$matrix[0][0]="t1";$matrix[0][1]="2j";$matrix[0][2]="r3";$matrix[0][3]="f8";$matrix[0][4]="y9";
$matrix[4][0]="i3";$matrix[4][1]="k7";$matrix[4][2]="a1";$matrix[4][3]="e3";$matrix[4][4]="f6";
$matrix[2][0]="t9";$matrix[2][1]="e2";$matrix[2][2]="w3";$matrix[2][3]="r2";$matrix[2][4]="w3";
shuffle($matrix);
//Shuffle the array
foreach($matrix as $key => $value) {
echo "$value
}
Can anyone help me solve this.
$shuffled_ = array();
$shuffled = array();
foreach( $matrix as $val )
foreach($val as $v)
$shuffled_[] = $v;
shuffle($shuffled_);
foreach( $shuffled_ as $key => $val )
$shuffled[ floor($key / 5) ][$key % 5] = $val;
It might be easier to dump all values into a single string, shuffle that and slice out a new password:
$original = 't9w3w3r2e296h3ooh545i2g5k439j9r3t1f82jy9e3f6a1k7i3';
$password = substr(str_shuffle($original), 0, 6); // generate 6-char password
Though, for password generation I would recommend using my other answer instead.
Your $matrix is multidimensional (specifically twodimensional) array, one foreach will just output the array, I think this is what u need
foreach($matrix as $matrixChild) {
shuffle($matrixChild); // updated
foreach ($matrixChild as $k => $value) {
echo $value;
}
}
EDIT
btw, why don't u use usual standard random string generator, smth like this
function generatePassword ($length = 8){
$password = "";
$i = 0;
$possible = "0123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
while ($i < $length){
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
What I'm trying to do is take a list of names (from input), lets say 100, shuffle them, then return a random selection based on a certain percentage (n) of the array.
For example, return 5%, which is 5 random names from the shuffled array if the array had 100 elements (names). I have tried Googling for a solution but couldn't find much and am at a loss and can't get past returning just a shuffled array.
(excerpt)
if(isset($_POST['submit']) === true) {
$names = $_POST['ShuffleNames'];
$namesArray = explode("\n", $names);
shuffle($namesArray);
//display each name on new line
foreach($namesArray as $name) {
echo "<li>". $name . "</li>";
}
}
You can do it as follows:
Accept the user inputs -- the array and percentage
Count the number of array elements using count()
Calculate the percentage: (count / percentage) * 100
Slice the array using array_slice() and return the result
As a function:
function array_percentage($array, $percentage)
{
shuffle($array);
$count = count($array);
$result = array_slice($array, 0, ceil($count*$percentage/100));
return $result;
}
You can use it like:
if(isset($_POST['submit'])) {
$names = $_POST['ShuffleNames'];
$namesArray = explode("\n", $names);
print_r(array_percentage($namesArray, 5));
}
Demo!
Almost there but instead of foreach:
$max = 5;
for ($i=0;$i<$max;++$i) {
echo "<li>".array_pop($namesArray). "</li>";
}
You can set $max to the percentage you want
if(isset($_POST['submit']) === true) {
$x = 5; //Set the percentage
$names = $_POST['ShuffleNames'];
$namesArray = explode("\n", $names);
$total = count($namesArray); //Get the total amount of elements (the 100%)
shuffle($namesArray);
//display each name on new line
for($i = 1; $i <= ($total/100)*$x; $i++) { //loop and output
echo "<li>". $namesArray[$i] . "</li>";
}
}
Use this: http://www.php.net/manual/en/function.str-shuffle.php
$names = $_POST['ShuffleNames'];
$namesArray = explode("\n", $names);
$names_Array = **str_shuffle**($namesArray);
// .. code ...
How can I randomize the results on this code ?
I have an array with more than four items on it, but I will like to get four of them only but not in order, how do I suppose to do that ? It can be done using foreach(array_slice ??
$i = 0;
foreach(array_slice($items_array,0,4) as $item) {
$output .= 'Item ID:'.$item['id'];
$i++;
}
My array
a:6:{i:0;a:4:{s:5:"title";s:17:"Spedition";s:2:"id";s:11:"ZCXbgH1JDt4";s:3:"url";s:40:"embed/ZCXbgH1JDt4";s:5:"image";s:38:"transport";}i:1;a:4:{s:5:"title";s:77:"DC......
$output = array_rand($items_array, 4);
array_rand()
Solved
$item = array_rand($items_array, 4); //get only four at random
$i=0;
while($i<=3) { // instead of 4 you set it at 3 because the counter starts at 0
$output = 'Item ID:'.$items_array[$item[$i]]['id'];
$i++;
}
Perfect Way for Get Random Value From Array
$numbers = range(1, 20);
shuffle($numbers); //this function will shuffle the array value
foreach ($numbers as $number) {
echo "$number ";
}
A better and easy solution would be using array_rand
$array = array("foo", "bar", "hallo", "world");
$rand_keys = array_rand($array,1);
echo $array[$rand_keys];
This should do it for you.
$i = 0;
foreach(array_rand($items_array, 4) as $item) {
$output .= 'Item ID:'.$item['id'];
$i++;
}
I want to select a random value from a array, but keep it unique as long as possible.
For example if I'm selecting a value 4 times from a array of 4 elements, the selected value should be random, but different every time.
If I'm selecting it 10 times from the same array of 4 elements, then obviously some values will be duplicated.
I have this right now, but I still get duplicate values, even if the loop is running 4 times:
$arr = $arr_history = ('abc', 'def', 'xyz', 'qqq');
for($i = 1; $i < 5; $i++){
if(empty($arr_history)) $arr_history = $arr;
$selected = $arr_history[array_rand($arr_history, 1)];
unset($arr_history[$selected]);
// do something with $selected here...
}
You almost have it right. The problem was the unset($arr_history[$selected]); line. The value of $selected isn't a key but in fact a value so the unset wouldn't work.
To keep it the same as what you have up there:
<?php
$arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');
for ( $i = 1; $i < 10; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Select a random key.
$key = array_rand($arr_history, 1);
// Save the record in $selected.
$selected = $arr_history[$key];
// Remove the key/pair from the array.
unset($arr_history[$key]);
// Echo the selected value.
echo $selected . PHP_EOL;
}
Or an example with a few less lines:
<?php
$arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');
for ( $i = 1; $i < 10; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Randomize the array.
array_rand($arr_history);
// Select the last value from the array.
$selected = array_pop($arr_history);
// Echo the selected value.
echo $selected . PHP_EOL;
}
How about shuffling the array, and popping items off.
When pop returns null, reset the array.
$orig = array(..);
$temp = $orig;
shuffle( $temp );
function getNextValue()
{
global $orig;
global $temp;
$val = array_pop( $temp );
if (is_null($val))
{
$temp = $orig;
shuffle( $temp );
$val = getNextValue();
}
return $val;
}
Of course, you'll want to encapsulate this better, and do better checking, and other such things.
http://codepad.org/sBMEsXJ1
<?php
$array = array('abc', 'def', 'xyz', 'qqq');
$numRandoms = 3;
$final = array();
$count = count($array);
if ($count >= $numRandoms) {
while (count($final) < $numRandoms) {
$random = $array[rand(0, $count - 1)];
if (!in_array($random, $final)) {
array_push($final, $random);
}
}
}
var_dump($final);
?>
Php has a native function called shuffle which you could use to randomly order the elements in the array. So what about this?
$arr = ('abc', 'def', 'xyz', 'qqq');
$random = shuffle($arr);
foreach($random as $number) {
echo $number;
}
key != value, use this:
$index = array_rand($arr_history, 1);
$selected = $arr_history[$index];
unset($arr_history[$index]);
I've done this to create a random 8 digit password for users:
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","m",
"n","p","q","r","s","t","u","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9");
for( $i=0;$i<=8;++$i ){
shuffle( $characters );
$new_pass .= $characters[0];
}
If you do not care about what particular values are in the array, you could try to implement a Linear Congruential Generator to generate all the values in the array.
LCG implementation
Wikipedia lists some values you can use, and the rules to select the values for the LCG algorithm, because the LCG algorith is deterministic it is guaranteed not to repeat a single value before the length of the period.
After filling the array with this unique numbers, you can simply get the numbers in the array 1 by 1 in order.
$isShowCategory = array();
for ($i=0; $i <5 ; $i++) {
$myCategory = array_rand($arrTrCategoryApp,1);
if (!in_array($myCategory, $isShowCategory)) {
$isShowCategory[] = $myCategory;
#do something
}
}
Easy and clean:
$colors = array('blue', 'green', 'orange');
$history = $colors;
function getColor($colors, &$history){
if(count($history)==0)
$history = $colors;
return array_pop( $history );
}
echo getColor($colors, $history);