php get two different random array elements [duplicate] - php

This question already has answers here:
How do I select 10 random things from a list in PHP?
(5 answers)
Closed 8 months ago.
From an array
$my_array = array('a','b','c','d','e');
I want to get two DIFFERENT random elements.
With the following code:
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
}
it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that?
Thanks

array_rand() can take two parameters, the array and the number of (different) elements you want to pick.
mixed array_rand ( array $input [, int $num_req = 1 ] )
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
echo $my_array[$key];
}

What about this?
$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.

You could always remove the element that you selected the first time round, then you wouldn't pick it again. If you don't want to modify the array create a copy.
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
unset($my_array[$random]);
}

You can shuffle and then pick a slice of two. Use another variable if you want to keep the original array intact.
$your_array=[1,2,3,4,5,6,7];
shuffle($your_array); // randomize the order
$your_array = array_slice($your_array, 0, 2); //pick 2

foreach (array_intersect_key($arr, array_flip(array_rand($arr, 2))) as $k => $v) {
echo "$k:$v\n";
}
//or
list($a, $b) = array_values(array_intersect_key($arr, array_flip(array_rand($arr, 2))));

here's a simple function I use for pulling multiple random elements from an array.
function get_random_elements( $array, $limit=0 ){
shuffle($array);
if ( $limit > 0 ) {
$array = array_splice($array, 0, $limit);
}
return $array;
}

Here's how I did it. Hopefully this helps anyone confused.
$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
echo $newArray[$i];
}

Get the first random, then use a do..while loop to get the second:
$random1 = array_rand($my_array);
do {
$random2 = array_rand($my_array);
} while($random1 == $random2);
This will keep looping until random2 is not the same as random1

Related

PHP: How to delete all array elements after an index [duplicate]

This question already has answers here:
php - how to remove all elements of an array after one specified
(3 answers)
Closed 9 years ago.
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray are not successive, I don't see a chance for array_slice()
Please note : Keys have to be preserved! + I do only know the Offset Key!!
Without making use of loops.
<?php
$myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
$offsetKey = 25; //<--- The offset you need to grab
//Lets do the code....
$n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
$new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
Output :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
Try
$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
See demo
I'd iterate over the array up until you reach the key you want to truncate the array thereafter, and add those items to a new - temporary array, then set the existing array to null, then assign the temp array to the existing array.
This uses a flag value to determine your limit:
$myArrayInit = array(1=>'red', 30=>'orange', 25=>'velvet', 45=>'pink');
$new_array = delIndex(30,$myArrayInit);
function delIndex($limit,$array){
$limit_reached=false;
foreach($array as $ind=>$val){
if($limit_reached==true){
unset($array[$ind]);
}
if($ind==$limit){
$limit_reached=true;
}
}
return $array;
}
print_r($new_array);
Try this:
function delIndex($afterIndex, $array){
$flag = false;
foreach($array as $key=>$val){
if($flag == true)
unset($array[$key]);
if($key == $afterIndex)
$flag = true;
}
return $array;
}
This code is not tested

generate random set of values from array

i want to get static length to get any random value from array.
PHP CODE:
in this below code how to get 5 random value from array?
$arr_history = array(23, 44,24,1,345,24,345,34,4,35,325,34,45,6457,57,12);
$lenght=5;
for ( $i = 1; $i < $lenght; $i++ )
echo array_rand($arr_history);
You can use array_rand() to pick 5 random keys and then use those to intersect with the array keys; this keeps the original array intact.
$values = array_intersect_key($arr_history, array_flip(array_rand($arr_history, 5)));
Demo
Alternatively, you can first shuffle the array in-place and then take the first or last 5 entries out:
shuffle($arr_history);
$values = array_slice($arr_history, -5);
This has the advantage that you can take multiple sets out consecutively without overlaps.
Try this :
$rand_value = array_rand($arr_history);
echo $rand_value;
REF: http://php.net/manual/en/function.array-rand.php
OR use :
shuffle($arr_history)
This will shuffle the order of the array : http://php.net/manual/en/function.shuffle.php

Shuffling Array in the same way, according to number

I am running a quiz making website. I wish to show the answers to a question to a user in a shuffled order.
I'm trying to avoid storing the order that answers were presented to the user, if I were to shuffle them randomly.
I want to shuffle the answers predictably, so that I can repeat the shuffle in the same way later (when displaying results).
I've thought that I could shuffle the list of answers by a certain number (either using the number within the sort, or having multiple types of sorts identifiable by an ID number. This way I can simply store the number that they were shuffled by and recall that number to reshuffle them again to the same order.
Here's the skeleton of what I have so far, but I don't have any logic to put the answers back in the $shuffled_array in the shuffled order.
<?php
function SortQuestions($answers, $sort_id)
{
// Blank array for newly shuffled answer order
$shuffled_answers = array();
// Get the number of answers to sort
$answer_count = count($questions);
// Loop through each answer and put them into the array by the $sort_id
foreach ($answers AS $answer_id => $answer)
{
// Logic here for sorting answers, by the $sort_id
// Putting the result in to $shuffled_answers
}
// Return the shuffled answers
return $shuffled_answers;
}
// Define an array of answers and their ID numbers as the key
$answers = array("1" => "A1", "2" => "A2", "3" => "A3", "4" => "A4", "5" => "A5");
// Do the sort by the number 5
SortQuestions($answers, 5);
?>
Is there technique that I can use to shuffle the answers by the number passed into the function?
PHP's shuffle function uses the random seed given with srand, so you can set a specific random seed for this.
Also, the shuffle method change's the array keys, but this is probably not the best outcome for you, so you may use a different shuffle function:
function shuffle_assoc(&$array, $random_seed) {
srand($random_seed);
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
This function will keep the original keys, but with a different order.
You could rotate the array by a factor.
$factor = 5;
$numbers = array(1,2,3,4);
for ( $i = 0; $i < $factor; $i++ ) {
array_push($numbers, array_shift($numbers));
}
print_r($numbers);
The factor can be randomized, and a function can switch the array back in place, by rotation the other way around.
This can be one of the possible ways.
$result = SortQuestions($answers, 30);
print_r($result);
function SortQuestions($answers, $num)
{
$answers = range(1, $num);
shuffle($answers);
return $answers;
}

php maximum values to show in a list in random order? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Output array elements randomly with PHP
Lets say we have this code:
<? if (isset($specialoffers)) { ?>
<? foreach ($specialoffers as $value) { ?>
<div>product #</div>
<?};?>
<?};?>
For example this list may be different everytime, it may have 1 product, and it may have 58 products. I want do display only 10 products in the list and in a random order.
How to do that?
I would like not to touch the SQL query!
Take a look at the array_rand function which takes one or more random elements from an array.
So, you could do something along the lines of:
foreach (array_rand($specialoffers,10) as $key)
do_something_interesting_with $specialoffers[$key];
$specialoffers = array_splice( shuffle($specialoffers), 0, 9 );
Something like this might work.
You can use shuffle() to randomize the array.
http://php.net/manual/en/function.shuffle.php
You can do that with Reservoir Sampling which is even needed if the number of elements would exhaust your memory (and are presented through an iterator):
$randoms = new RandomIterator($specialoffers, 10);
foreach ($randoms as $value) {
...
}
You can find the source-code of the RandomIterator class as Gist.
Please try example for getting random value from assoc arrays;
function array_random_assoc( $arr, $num = 1) {
$keys = array_keys($arr);
shuffle($keys);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[$keys[$i]] = $arr[$keys[$i]];
}
return $r;
}
$specialoffers = (array_random_assoc($data_array, 10));

php arrays get the order number of a certain element

Lets say i have an array in PHP
$test['michael_unique_id'] = 3;
$test['john_unique_id'] = 8;
$test['mary_unique_id'] = 10;
.
.
.
.
$test['jimmy_unique_id'] = 4;
(the values (3,8,10.........4) are unique)
Lets say i want to search for the unique id 10, and get the order of the matching element in the array. In this example, the third element has the value 10, so i should get the number 3.
I can do it by scanning with a for loop looking for the value i'm searching and then get the $i value when i have a match, but i wonder if there is any built-in function (or a better method) that implements this.
You can get all of the array's values as an array with array_values() and then use array_search() to get the position (offset) of that value in the array.
$uniq_id = 10;
$all_vals = array_values($test); // => array(3, 8, 10, ... )
echo array_search( $uniq_id, $all_vals ); // => 2
Because PHP array indices are zero-based, you'll get 0 for the first item, 1 for the second item, etc. If you want the first item to be "1," then just add one. All together now:
$uniq_id = 10;
echo array_search( $uniq_id, array_values( $test ) ) + 1; // => 3
It's not clear to me, however, that this is necessarily as performant as just doing a foreach:
$uniq_id = 10;
$idx = 1;
foreach($test as $val) {
if($val == $uniq_id) {
break;
}
$idx++;
}
echo $idx; // => 3
Well, array_search will give you the key, but in your case, you want the index of that key, so I believe a loop is your best bet. Is there a good reason why you need the index? It doesn't seem very useful to me.

Categories