Output array elements randomly with PHP - php

How could I echo 5 elements randomly from an array of about 20?
Thanks.

Does this work?
$values = array_rand($input, 5);
Or, as a more flexible function
function randomValues($input, $num = 5) {
return array_rand($input, $num);
}
//usage
$array = range('a', 'z');
//prints 5 random characters from the alphabet
print_R(randomValues($array));

for($i=0; $i++; $i < 5)
{
echo $array[rand(0, count($array)-1);
}
or
for($i=0; $i++; $i < 5)
{
echo array_rand($array);
}
or
array_map("echo", array_rand($array, 5));

$n = number of random numbers to return in the array
$min = minimum number
$max = maximum number
function uniqueRand($n, $min = 0, $max = null)
{
if($max === null)
$max = getrandmax();
$array = range($min, $max);
$return = array();
$keys = array_rand($array, $n);
foreach($keys as $key)
$return[] = $array[$key];
return $return;
}
$randNums = uniqueRand(5, 0, count($array)-1);
for($i=0; $i++; $i < 5)
{
echo $array[$randNums[i]);
}

Related

How to condense an array of integers in PHP?

So I have an array of integers: <1, 2, 3, 9, 10, 11, 14>, that I would like to join together in this format: <1-3, 9-11, 14>.
I'm new to PHP and tried doing this by looping through the array:
function pasteTogether($val)
{
$newVals = array();
$min = $val[0];
$max = $val[1];
$counter = 0;
for ($i = 0; $i < count($val); $i++)
{
if ($val[$i + 1] === $val[$i] + 1)
{
$max = $val[$i + 1];
}
else
{
$tempVal = $min."-".$max;
$newVals[$counter] = $tempVal;
$counter++;
$min = $val[$i];
}
}
return $newVals;
}
However, when I run this code, I get <1-3, 3-11, 11-11, 14-14>
PHP Fatal error: Maximum execution time of 30 seconds exceeded in ../learning.php on line 36
Because the for loop never ends you increment $val instead of $i
$array = array(1, 2, 3, 9, 10, 11, 14);
function pasteTogether($val)
{
$newVals = array();
$min = $val[0];
$max = $val[1];
$counter = 0;
for ($i = 0; $i < count($val); $i++)
{
if ($val[$i + 1] === $val[$i] + 1)
{
$max = $val[$i + 1];
}
else
{
$tempVal = $min."-".$max;
$newVals[$counter] = $tempVal;
$counter++;
$min = $val[$i];
}
}
return $newVals;
}
pasteTogether($array);
I have been playing around with this interesting problem and found another solution. So, if anyone is interested:
$arr=array(1, 2, 3, 9, 10, 11, 14, 15, 16, 18);
$v0=$dif=null;$rows=array();
foreach ($arr as $i => $v) {
if ($dif!=($d=($v-$i))){
if ($v0) $rows[]="$v0-".$arr[$i-1];
$v0=$v;
$dif=$d;
}
}
$rows[]="$v0-".($d==$dif?$arr[$i]:$v0);
print_r($rows);
I added a few numbers to the array and the result is this:
$rows = Array
(
[0] => 1-3
[1] => 9-11
[2] => 14-16
[3] => 18-18
)
You can find a little demo here: http://rextester.com/ABC25608
This works:
function pasteTogether($val)
{
$compacted = [];
$min = null;
$max = null;
$format = function ($a, $b) {
return ($a < $b ? "$a-$b" : $a);
};
foreach ($val as $current) {
if ($min === null) {
$min = $current;
$max = $current - 1;
}
if ($current == $max + 1) {
$max++;
} else {
$compacted[] = $format($min, $max);
$min = $current;
$max = $current;
}
}
$compacted[] = $format($min, $max);
return $compacted;
}
echo '<', implode(', ', pasteTogether([1, 2, 3, 9, 10, 11, 14])), '>';
Output:
<1-3, 9-11, 14>

PHP - How to create all possibility from a string

Here, there is a example string "XjYAKpR" .. how to create all new string possibility with that string ??
I've tried before
function containAllRots($s, $arr) {
$n = strlen($s);
$a = array();
for ($i = 0; $i < $n ; $i++) {
$rotated = rotate(str_split($s), $i);
$a[] = $rotated;
}
print_r($a);die();
if (array_diff($arr, $a)) {
return True;
}
else
{
return False;
}
}
I make 2 function rotate and generate
function rotate($l, $n) {
$b = $l[$n];
$sisa = array_values(array_diff($l, array($b)));
for ($i = 0; $i < count($sisa) ; $i++) {
$random[] = generate($sisa, $b);
}
print_r($random);die();
$hasil = $l[$n] . implode("",$random);
return $hasil;
}
function generate($sisa, $b) {
$string = implode("",$sisa);
$length = count($sisa);
$size = strlen($string);
$str = '';
for( $i = 0; $i < $length; $i++ ) {
$str .= $string[ rand( 0, $size - 1 ) ];
}
Here there is a pair of functions that lets you calculate a permutation set
(no repetitions are taken in account)
function extends_permutation($char, $perm) {
$result = [];
$times = count($perm);
for ($i=0; $i<$times; $i++) {
$temp = $perm;
array_splice($temp, $i, 0, $char);
array_push($result, $temp);
}
array_push($result, array_merge($perm, [$char]));
return $result;
}
function extends_set_of_permutations($char, $set) {
$step = [];
foreach ($set as $perm) {
$step = array_merge($step, extends_permutation($char, $perm));
}
return $step;
}
you can use them to generate the required set of permutations. Something like this:
$seed = "XjYAKpR";
// the first set of permutations contains only the
// possible permutation of a one char string (1)
$result_set = [[$seed[0]]];
$rest = str_split(substr($seed,1));
foreach($rest as $char) {
$result_set = extends_set_of_permutations($char, $result_set);
}
$result_set = array_map('implode', $result_set);
sort($result_set);
At the end of the execution you will have the 5040 permutations generated by your string in the result_set array (sorted in alphabetical order).
Add a char and you will have more than 40000 results.
The functions are quite naive in implementation and naming, both aspects can be improved.

php random number with number(1-9) only 6 length

I want only 6 random numbers [length = 6] from 0,1,2,3,4,5,6,7,8,9 in php function without duplicates.
This is my code
$a = mt_rand(1,9999999999); //because I need from 1 to 9999999999 of(0,1,2,3,4,5,6,7,8,9)
for ($i = 0; $i<6; $i++)
{
$a .= mt_rand(0,9);
}
I am not sure my code is good solution or not
How I can do it?
Try this code.
function GenerateRandom($min, $max, $range) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $range);
}
print_r( GenerateRandom(0,25,6) );
Hope this helps.
If your source array is rather big, you may save some memory by only fetching what you need:
$a = range(0, 9);
for ($i = 0, $n = count($a); $i < 6 && --$n; ++$i) {
$r = mt_rand(0, $n);
if ($r != $n) {
$tmp = $a[$n];
$a[$n] = $a[$r];
$a[$r] = $tmp;
}
}
echo join(',', array_slice($a, -6));
I'm coining the term "Partial Knuth Shuffle" for this.

How do I get the highest value when using loops?

I want to get the highest value of my array.
This are the two ways when I'm working with php functions.
$a = array(1,125,1068);
1. $value = max($a);
print_r ($value);
2. asort($a);
$value = end($a);
print_r ($value);
I just couldn't figure out how to get the highest value when using loops.
You do it like this:
$highest = 0;
//if you have negative values: $highest = min($a);
foreach($a as $item){
if ($item > $highest){
$highest = $item;
}
}
Without using the max() function, you can do something like
<?php
$a = array(1,125,1068)
$max = $a[0];
for ($i = 1; $i <count($a); $i++) {
if ($a[$i] > $max) {
$max = $a[$i];
}
}
echo $max;
?>
max()
http://php.net/manual/en/function.max.php
$dd = array(50, -25, -5, 80, -40, -152, -45, 28, -455, 100, 98, -455);
$curr = '';
$max = $dd[0];
for($i = 0; $i < count($dd); $i++) {
$curr = $dd[$i];
if($curr >= $max) {
$max = $curr;
}
}

PHP make all possible variants of 4char A-Z,a-z,0-9

I have to make a list of all possible permurations of 4characters A-Z,a-z,0-9 and conbination of all this.How can i pass thru all of the possible combinations and printf them ?
what's it for:I need to make this in a html document that i can then print and give all this as random unique usernames for our university, so that students can provide feedback based on one unique id that will be invalidated when used. i can not change this procedure into a better one!
Warning: This takes some time to compute because there are 62^4 = 14776336 possible combinations. It also takes a lot of memory if you accumulate the results and don't print them directly.
function print_combinations($characters, $length, $combination = '') {
if ($length > 0) {
foreach ($characters as $i) {
print_combinations($characters, $length - 1, $combination . $i);
}
} else {
printf("%s\n", $combination);
}
}
$characters = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
print_combinations($characters, 4);
With a rather unconventional approach, you could use dec2any from the comments on the php documentation for base_convert like this:
$index = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($index);
$len = 4;
for ($i = 0, $l = pow(strlen($index), $len); $i < $l; $i++) {
echo str_pad(dec2any($i, $base, $index), $len, "0", STR_PAD_LEFT), "\n";
}
function dec2any( $num, $base=62, $index=false ) {
if (! $base ) {
$base = strlen( $index );
} else if (! $index ) {
$index = substr( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base );
}
$out = "";
for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) {
$a = floor( $num / pow( $base, $t ) );
$out = $out . substr( $index, $a, 1 );
$num = $num - ( $a * pow( $base, $t ) );
}
return $out;
}
It can be quite easily adapted by changing $index and $len.
It's a little rushed but:
class Combinations{
protected $characters = array();
protected $combinations = array();
public function __construct($characters){
$this->characters = $characters;
}
public function getCombinations($length){
foreach($this->characters as $comb)
{
$this->getRecurse($comb, $length - 1);
}
$combinations = $this->combinations;
$this->combinations = array();
return $combinations;
}
public function getRecurse($combination, $length){
if($length <= 0){
$this->combinations[] = $combination;
}else{
foreach($this->characters as $comb)
{
$this->getRecurse($combination.$comb, $length - 1);
}
}
}
}
$characters = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
$comb = new Combinations($characters);
print_r( $comb->getCombinations(4) );
The number passed to getCombinations is how long you want the combinations to be.
More universal approach with delimiter :
function getCombinations($base,$delimiter="|"){
$base = array_values($base);
$baselen = count($base);
if($baselen == 0){
return;
}
if($baselen == 1){
return $base[0];
}else{
//get one level lower combinations
$oneLevelLowerArray = $base;
$orig_part = $oneLevelLowerArray[0];
unset($oneLevelLowerArray[0]);
$oneLevelLower = getCombinations($oneLevelLowerArray,$delimiter);
$countOLL = count($oneLevelLower);
foreach ($orig_part as $rowa) {
foreach ($oneLevelLower as $rowb) {
$resultArray[] = $rowa.$delimiter.$rowb;
}
}
}
return $resultArray;
}
Something like that? (pseudo code)
$a = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
foreach($a as $key => $b) {
echo $b.$a[$key+1].$a[$key+2].$a[$key+3].'<br />';
}
$numbers = range(0, 9);
$lowerCaseLetters = range('a', 'z');
$upperCaseLetters = range('A', 'Z');
foreach($numbers as $number) {
foreach($lowerCaseLetters as $lowerCaseLetter) {
foreach($uperCaseLetters as $upperCaseLetter) {
echo $number.$lowerCaseLetter.$upperCaseLetter.'<br />';
echo $number.$upperCaseLetter.$lowerCaseLetter.'<br />';
echo $lowerCaseLetter.$number.$upperCaseLetter.'<br />';
echo $lowerCaseLetter.$upperCaseLetter.$number.'<br />';
echo $upperCaseLetter.$lowerCaseLetter.$number.'<br />';
echo $upperCaseLetter.$number.$lowerCaseLetter.'<br />';
}
}
}

Categories