PHP Random Shuffle Array Maintaining Key = Value
The first user post under the shuffle
documentation:
Shuffle associative and
non-associative array while preserving
key, value pairs. Also returns the
shuffled array instead of shuffling it
in place.
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
Test case:
$arr = array();
$arr[] = array('id' => 5, 'foo' => 'hello');
$arr[] = array('id' => 7, 'foo' => 'byebye');
$arr[] = array('id' => 9, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
print_r(shuffle_assoc($arr));
PHP shuffle numerically indexed object array preserve key-value
You can loop through the array and then randomly exchange the values in it.
for($x=0;$x<count($array);$x++){
$temp=$array[$x];
$index=rand(0,count($array)-1);
$array[x]=$array[$index];
$array[$index]=$temp;
}
Working example below.
<?php
$array=array();
$array[0]['name'] = "John";
$array[0]['lastname'] = "Blabla";
$array[0]['genre'] = "Male";
$array[1]['name'] = "Cheryl";
$array[1]['lastname'] = "Blabla";
$array[1]['genre'] = "Female";
$array[2]['name'] = "Amy";
$array[2]['lastname'] = "Blabla";
$array[2]['genre'] = "Female";
$array[3]['name'] = "Adam";
$array[3]['lastname'] = "Blabla";
$array[3]['genre'] = "Female";
$array[4]['name'] = "Hitan";
$array[4]['lastname'] = "Blabla";
$array[4]['genre'] = "Male";
$array[5]['name'] = "Mary";
$array[5]['lastname'] = "Blabla";
$array[5]['genre'] = "Female";
for($x=0;$x<count($array);$x++){
$temp=$array[$x];
$index=rand(0,count($array)-1);
$array[$x]=$array[$index];
$array[$index]=$temp;
}
var_dump($array);
How to get random value out of an array?
You can also do just:
$k = array_rand($array);
$v = $array[$k];
This is the way to do it when you have an associative array.
shuffle() doesn't work as expected with an associative array
From the manual for shuffle()
(emphasis mine):
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
Here's a solution for associative arrays from the comments of that page:
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
Credits goes to: "ahmad at ahmadnassri dot com"
PHP Array shuffle, keeping unique
You can use this function:
<?php
function shuffleArray($myArray) {
$value_count = array_count_values($myArray);
foreach($value_count as $key=>$value) {
if ($value > count($myArray)/2) {
return false;
}
}
$last_value = $myArray[count($myArray) - 1];
unset($myArray[count($myArray) - 1]);
$shuffle = array();
$last = false;
while (count($myArray) > 0) {
$keys = array_keys($myArray);
$i = round(rand(0, count($keys) - 1));
while ($last === $myArray[$keys[$i]]) {
$i = round(rand(0, count($keys) - 1));
}
$shuffle[] = $myArray[$keys[$i]];
$last = $myArray[$keys[$i]];
unset($myArray[$keys[$i]]);
}
if ($last_value === $last) {
$i = 0;
foreach($shuffle as $key=>$value) {
if ($value !== $last_value) {
$i = $key;
break;
}
}
array_splice($shuffle, $i + 1, 0, $last_value);
} else {
$shuffle[] = $last_value;
}
return $shuffle;
}
print_r(shuffleArray(array(1,5,5,3,7,7)));
php, how to jumble / randomize order of associative array while keeping key/value pairs
You could use shuffle() on array_keys, then loop around your array adding them to the list in the new order.
E.g.
$shuffleKeys = array_keys($array);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $array[$key];
}
How to shuffle list in PHP
print_r
function display data as they are. So it print array when you give it array. You need to implode your array into string:
echo implode('',shuffle_assoc($arr));
edit:
or just
echo implode('',shuffle($arr));
php get random unique value from an array without repeating & also preserve & get the key
One way to achieve your desired result is to write a function which returns a random value from the $fruit
array, going through all values in the array and then shuffling the array before returning the next set of values. Since we can't shuffle
an array without losing the keys, this function stores the keys of the $fruit
array and shuffles them instead:
function random_fruit() {
static $i = 0;
static $fruit = [
'f1' => 'mango',
'f2' => 'pear',
'f3' => 'apple',
'f4' => 'banana',
];
// would be nice to write:
// static $keys = array_keys($fruit);
// but PHP doesn't allow it so we have to assign the value
// the first time we call the function
static $keys;
if ($i == 0) $keys = array_keys($fruit);
$length = count($fruit);
if ($i % $length == 0) shuffle($keys);
return array($keys[$i % $length], $fruit[$keys[$i++ % $length]]);
}
Then every time you want a new fruit, you can simply call the random_fruit
function. For example, to output 20 random fruits:
for ($j = 0; $j < 20; $j++) {
list($key, $fruitvalue) = random_fruit();
echo "$key: $fruitvalue\n";
if ($j % 4 == 3) echo "-----\n";
}
Sample output:
f4: banana
f2: pear
f1: mango
f3: apple
-----
f4: banana
f1: mango
f3: apple
f2: pear
-----
f3: apple
f2: pear
f4: banana
f1: mango
-----
f3: apple
f1: mango
f4: banana
f2: pear
-----
f4: banana
f1: mango
f2: pear
f3: apple
-----
Demo on 3v4l.org
PHP random string generator
To answer this question specifically, two problems:
$randstring
is not in scope when you echo it.- The characters are not getting concatenated together in the loop.
Here's a code snippet with the corrections:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Output the random string with the call below:
// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.
Related Topics
New Limit Within PHP: 1000 Fields Per Post. Does Someone Know, If the Number Can Be Influenced
Utf-8 Encoded HTML Pages Show Questions Marks Instead of Characters
Regex Backreference to Match Different Values
Turn Off Warnings and Errors on PHP and MySQL
Php: Possible to Automatically Get All Posted Data
PHP Header() Redirect with Post Variables
PHP Curl: I Need a Simple Post Request and Retrival of Page Example
How to Read "Fetch(Pdo::Fetch_Assoc);"
Remove All the Line Breaks from the HTML Source
How to Call Codeigniter Controller Function from View
Casting an Array with Numeric Keys as an Object
Array_Multisort and Dynamic Variable Options
Why Should I Use Templating System in PHP
How to Read a List of Files from a Folder Using PHP