How to Shuffle array - php

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;
}

Related

Build string on one line PHP

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

How to extract adjacent pair of words in associative array in php?

I have an associative array in PHP like this:
$weight["a"]=1;
$weight["b"]=4;
$weight["c"]=5;
$weight["d"]=9;
Here I want to calculate pair-wise difference between consecutive array elements, e.g.,
"b-a" = 3
"c-b" = 1
"d-c" = 4
How should this be computed?
Try this:
$i = 0;
foreach ($weight AS $curr) {
if ($i > 0) {
echo '"'.array_keys($weight)[$i].'-'.array_keys($weight)[$i-1].'" = '.($curr-$prev)."<br />";
}
$i++;
$prev = $curr;
}
Store keys on a temporary array where keys are integers on which you can easily get the next key, and use it to parse your main array.
$tmp_array = array();
foreach ($weight as $key => $val) {
$tmp_array[] = $key;
}
$array_length = count($tmp_array);
for ($i = 0; i < array_length - 2; ++$i) {
echo $weight[$tmp_array[$i+1]], '-', $weight[$tmp_array[$i]], ' = ', ($weight[$tmp_array[$i+1]] - $weight[$tmp_array[$i]], PHP_EOL;
}

Get random values from array on PHP using foreach and array_slice?

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++;
}

Determining duplicate letter counts between an array of strings

I have an array of strings of random letters, and I need to know which letters are consistent between the array members. The count of the letters are important.
My method right now is loop through the array, doing a split, then looping through the spitted string to count the occurrences of each letter, then update the array with letter => count
Then do an array_reduce that creates a new array of members who only occur in all arrays. But, it's not working.
<?
$a[] = "emaijuqqrauw";
$a[] = "aaeggimqruuz";
$a[] = "aabimqrtuuzw";
$a[] = "aacikmqruuxz";
$a[] = "aacikmqruuxz";
$a[] = "aaciimqruuxy";
foreach($a as $b){
$n = str_split($b, 1);
foreach($n as $z){
$arr[$z] = substr_count($b, $z);
}
ksort($arr);
$array[] = $arr;
unset($arr);
}
$n = array_reduce($array, function($result, $item){
if($result === null){
return $item;
}else{
foreach($item as $key => $val){
if(isset($result[$key])){
$new[$key] = $val;
}
}
return $new;
}
});
foreach($n as $key => $val){
echo str_repeat($key, $val);
}
This returns aaiimqruu - which is kinda right, but there's only 2 i's in the last element of the array. There's only one i in the rest. I'm not sure how to break that down farther and get it to return aaimqruu- which I'll then pop into a SQL query to find a matching word, aquarium
There's array_intersect(), which is most likely what you'd want. Given your $a array, you'd do something like:
$a = array(.... your array...);
$cnt = count($a);
for($i = 0; $i < $cnt; $i++) {
$a[$i] = explode('', $a[$i]); // split each string into array of letters
}
$common = $a[0]; // save the first element
for($i = 1; $i < $cnt; $i++) {
$common = array_intersect($common, $a[$i]);
}
var_dump($common);
How about you do it this way? Finds out the occurrence of an item throughout the array.
function findDuplicate($string, $array) {
$count = 0;
foreach($array as $item) {
$pieces = str_split($item);
$pcount= array_count_values($pieces);
if(isset($pcount[$string])) {
$count += $pcount[$string];
}
}
return $count;
}
echo findDuplicate("a",$a);
Tested :)
Gives 12, using your array, which is correct.
Update
My solution above already had your answer
$pieces = str_split($item);
$pcount= array_count_values($pieces);
//$pcount contains, every count like [a] => 2
Seems like array_reduce is the best function for what this purpose, however I just didn't think of adding a conditional to give me the desired effect.
$new[$key] = ($result[$key] > $val) ? $val : $result[$key];
to replace
$new[$key] = $val;
did the trick.

get random value from a PHP array, but make it unique

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);

Categories