I am doing a little function to generate random usernames, as the following:
public static function nicknames($data) {
if ($data['request'] == 'nickAvailable') {
foreach ($data as $value)
if (is_array($value))
$nick = $value['nickname'];
$random = rand(2, 2);
$nickname = $nick . '_' . $random;
$count = 3;
$nicknames = array();
for ($i = 1; $i <= $count; $i++) {
$select = self::$db->select('users', 'nickname', array('nickname' => $nickname));
if (count($select) == 0) {
$nicknames[] = $nickname;
} else {
$count = $count + 1;
}
}
$array = array("status" => 0,
"errors" => $nicknames,
"data" => array());
model::json($array);
}
}
The only problem I have is that $random is just executed one time and not on each loop. I need 3 different usernames to be in the array, and they must be different from each other.
How can I edit my code to achieve this?
Thanks for any suggestion
Place the random number generator and nickname building variable at the start of your loop. Also increase the range of numbers that rand is allowed to return, as it will always return 2 at the moment
$usernames = array();
do {
// inside generate random number,
// build nickname,
// query to see if its taken,
// and if NOT taken, add to the usernames array
} while(count($usernames) < 3);
As of now, you're not generating a random number.
$random = rand(2, 2);
This will always be 2.
Here's how I'd do it:
for ($i = 1; $i <= $count; $i++)
{
$random = rand(1, 3);
$nickname = $nick . '_' . $random;
$select = self::$db->select('users', 'nickname', array('nickname' => $nickname));
if (count($select) == 0) {
$nicknames[] = $nickname;
} else {
$count = $count + 1;
}
}
Hope this helps!
Related
i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>
I'm having the problem that i want to echo the class $password as often, as the number of $intcount is. Can you give me any idea how I would do that?
f.e. that I echo 4 random words if $intcount is 4, 5 words if its 5 etc etc.
<?php
$csv = array_map('str_getcsv', file('gen.csv'));
$count = $_GET['count'];
$intcount = (int)$count;
$min = 0;
$max = 4;
$rand = mt_rand( $min , $max );
$out = $csv[$rand][$rand];
$password = $out;
// var_dump($count);
// var_dump($intcount);
//
// echo $count . "\n <br>";
// echo $password * $intcount;
//
// for ($i=0; $i < $intcount ; $i++) {
// echo $password;
// }
?>
The commented code doesn't need to stay necessarily.
Thanks :)
You need to create the $rand inside the loop like:
$csv = array_map('str_getcsv', file('gen.csv'));
$count = $_GET['count'];
$intcount = (int)$count;
$min = 0;
$max = 4;
for ($i=0; $i < $intcount ; $i++)
{
$rand = mt_rand($min, $max);
$password = $csv[$rand][$rand];
echo $password;
}
I have this loop:
for ($i = 0; $i < 9; $i++) {
$random_number = rand(1, 9);
if (!in_array($section_one, $random_number)) {
array_push($section_one, rand(1, 9));
}
}
As you can see the if statement in the loop checks if the generated random number is already in the array called $section_one. The problem is that if the random number is in the array, a new random number should be generated. Doing this ones is easy, but it has to keep regenerating a random number until a unique one has been generated.
How can I do that?
$run = true;
$max = 9;
$section_one = [];
while ($run) {
$rand = rand(1,$max);
if(!in_array($rand, $section_one)){
array_push($section_one, $rand);
}
if(count($section_one) >= $max) $run = false;
}
The idea is running loop until $section_one got full unique numbers.
try this:
$section_one = array();
for ($i = 0; $i < 9; $i++) {
$random_number = rand(1, 9);
if (!in_array($random_number,$section_one)) {
array_push($section_one, $random_number);
}
}
var_dump($section_one);
I want to generate 10 numbers with each ranging from (1 to 5) but can only duplicate after 2 elements
for example 5 3 1 4 2 5(can be duplicated here) 2 (cannot be duplicate here since it occur before 1 element) ...etc.
I have this code in php working but its performance is awful since it sometimes exceeds the maximum 30 seconds execution time.
<?php
function contain($prevItems, $number) {
if (count($prevItems) == 3)
{
array_shift($prevItems);
}
for ($k=0; $k<count($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,5);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,5);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,5);
}
$prevItems[$i] = $num[$i]; //append into the array
}
print_r($num);
?>
Edit:
I have also tried this method, its performance is good but it duplicates elements
<?php
$evalAccurance = array();
$count = 0;
while ( $count < 11)
{
$random = rand(1, 5);
if (in_array($random, $evalAccurance))
{
$p = $random;
for ($k = $p ; $k <5; $k++)
{
$random = $random++;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
if (in_array($random, $evalAccurance))
{
for ($k = $p ; $k >0; $k--)
{
$random = $random--;
if (in_array($random, $evalAccurance))
continue 1;
else break 1;
}
}
}
$evalAccurance[] = $random;
if (count ($evalAccurance) == 4)
array_shift($evalAccurance);
print_r ($evalAccurance);
$count++;
}
?>
One way you could do this:
// pass to function current array of numbers
function randomNumber($ar){
// create a random number from 1 to 5
$num = rand(1,5);
// check backwards 3 elements for same number, if none found return it
if(!in_array($num, array_slice($ar, -3, 3, true))){
return $num;
} else {
// else recall function with same array of numbers
return randomNumber($ar);
}
}
$array = array();
// loop 10 numbers and call randomNumber with current set of results.
for($i=1; $i<=10; $i++){
$array[] = randomNumber($array);
}
print_r($array);
Using PHP SPLQueue:
$queue = new SplQueue();
$values = array(1, 2, 3, 4, 5);
$container = array();
for ($i = 0; $i < 10; $i++) {
$value = give_random($values, $queue);
$container[] = $value;
if ($queue->offsetExists(1) AND $queue->offsetExists(0)) {
$queue->dequeue();
}
$queue->enqueue($value);
}
function give_random(&$values, &$queue) {
$picked_value = $values[array_rand($values)];
if ($queue->offsetExists(1)) {
if ($picked_value == $queue->offsetGet(1)) {
$picked_value = give_random($values, $queue);
}
}
if ($queue->offsetExists(0)) {
if ($picked_value == $queue->offsetGet(0)) {
$picked_value = give_random($values, $queue);
}
}
return $picked_value;
}
print_r($container);
It could be neater, but you can figure what's going on.
Cheers.
How can I select a random set of rows
The important bits:
I need to specify the number of random rows to select via a variable.
Say for instance the number of rows I want to select is 10, then it HAS TO select 10 DIFFERENT rows. I don't want it to pick out the same row a few times until it has 10.
The code below picks out 1 random row, how can I tailor this to the above spec?
<?php $rows = get_field('repeater_field_name');
$row_count = count($rows);
$i = rand(0, $row_count - 1);
echo $rows[$i]['sub_field_name']; ?>
<?php
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$rand_rows = array();
for ($i = 0; $i < min($row_count, 10); $i++) {
// Find an index we haven't used already (FYI - this will not scale
// well for large $row_count...)
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['sub_field_name'];
}
?>
This is a better implementation:
<?
$rows_i_want = 10;
$rows = get_field('repeater_field_name');
// Pull out 10 random rows
$rand = array_rand($rows, min(count($rows), $rows_i_want));
// Shuffle the array
shuffle($rand);
foreach ($rand as $row) {
echo $rows[$row]['sub_field_name'];
}
?>
Simply loop through the random row process the number of random rows you want to get.
<?php
$rows_to_get=10;
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$x=0
while($x<$rows_to_get){
echo $rows[rand(0, $row_count - 1)]['sub_field_name'];
$x++;
}
?>
You can give this a try
$rows = get_field('repeater_field_name');
var_dump(__myRand($rows, 10));
function __myRand($rows, $total = 1) {
$rowCount = count($rows);
$output = array();
$x = 0;
$i = mt_rand(0, $rowCount - 1);
while ( $x < $total ) {
if (array_key_exists($i, $output)) {
$i = mt_rand(0, $rowCount - 1);
} else {
$output[$i] = $rows[$i]['sub_field_name'];
$x ++;
}
}
return $output ;
}
A simple solution :
$rows = get_field('repeater_field_name');
$limit = 10;
// build new array
$data = array();
foreach ($rows as $r) { $data[] = $r['sub_field_name']; }
shuffle($data);
$data = array_slice($data, 0, min(count($data), $limit));
foreach ($data as $val) {
// do what you want
echo $val;
}