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
Related
I'm trying to create a random number generator in PHP. It's supposed to generate three (3) numbers at a time, without repeat. That's to say, the 3 numbers cannot be the same.
Here's what I've tried so far:
$array = [];
$A = mt_rand(1,36);
$array[0] = $A;
$B = mt_rand(1,36);
$array[1] = $B;
if(in_array($B,$array)){
$B = mt_rand(1,36);
$array[1] = $B;
}
$C = mt_rand(1,36);
$array[2] = $C;
if(in_array($C,$array)){
$C = mt_rand(1,36);
$array[2] = $C;
}
$length = count($array);
//display the array values;
for($i = 0; $i < $length; $i++){
echo ($array[$i]."<br>");
}
Can anyone tell me where I'm going wrong?
Like this ( as per my initial comment ),
$array = [];
while( count($array) < 3 ){
$rand = mt_rand(1,36);
$array[$rand] = $rand;
}
print_r( $array );
By setting the "key" to be the random number, we can abuse the fact that associative array keys are unique. Then it's a simple matter of waiting until the array contains the desired amount of unique items.
You can test it here
Outputs: ( your results may vary, it's random )
Array
(
[16] => 16
[20] => 20
[27] => 27
)
UPDATE I was trying to think of a valid way to do it without using a loop ( on my way home from work ), and this way may be even better in some cases.
$a = range(1,36);
shuffle($a);
$array = array_slice($a, 0, 3);
print_r($array);
This will have better performance when the number of items you must find is higher. This is because there is no repetition, no collisions. So if you have a small range but need to find many items for the return, this will preform better. If you have many items and need to return only few, then the first one may be better, if not from speed then from memory use.
You can see it here
For reference this uses
range() - Create an array containing a range of elements.
http://php.net/manual/en/function.range.php
shuffle() - Shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.
http://php.net/manual/en/function.shuffle.php
array_slice() - Returns the sequence of elements from the array as specified by the offset and length parameters.
http://php.net/manual/en/function.array-slice.php
So to explain this last one
First we create an array that contains each of our possible numbers as an element. So for example like this [1,2,3,4,5,6, ...].
Next we shuffle it which randomizes the order of the whole array. Shuffle modifies the array by "reference" so it doesn't return our array and therefor there is no assignment ( I think it returns Boolean, however I'm at a loss as to how it could fail and return false, pretty much it just returns true which we don't want to overwrite our array with ). So our example then becomes this [16,20,27,14,5,1, ...]
Last we cut out the number of items we need to return. Finally we end the example with this [16,20,27];
You can crunch the first one down into one ( really 2) line by assigning the value of the $rand variable in the condition of the loop. Like this:
$array = [];
while( count($array) < 3 && false !== ($rand = mt_rand(1,36))) $array[$rand] = $rand;
Because mt_rand(1,36) will never return boolan false. Also if I remember mt_rand is the same as rand now, or at least in current PHP versions.
Note: As of PHP 7.1.0, rand() uses the same random number generator as mt_rand(). To preserve backwards compatibility rand() allows max to be smaller than min as opposed to returning FALSE as mt_rand(). http://php.net/manual/en/function.rand.php
Hope it helps you, remember to think outside of the box.
I want to make an array with the same value and set the array to be maximum based on my counter.
For example, I want to create an array with a string "hello" and I want it to keep going until the number of array is 3.
How is that possible using php with yii2 framework?
you can use a for loop this way
$array= array();
for($i=0;$i<3;$i++){
$array[] = "hello";
}
You will get $array with 3 hello.
try array_fill
$count = 5;
$a = array_fill(0, $count, 'hello');
I have a multidimensional array:
$arr = array(
array('lions', 'tigers', 'bears'), // count = 3
array('dogs', 'cats'), // count = 2
array('horses', 'pigs', 'cattle', 'sheep', 'chickens') // count = 5
);
I want to return the array with the lowest count (I don't need to know the count, just need the array that HAS the lowest count). In this case, array('dogs', 'cats')
Right now I have:
$lowest = null;
foreach($nodePath as $arr)
{
$lowest = count($arr) < count($lowest) || $lowest == null ? $arr : $lowest;
}
This works but I'm wondering if I missed a more contained solution, perhaps using array_map, array_walk or a similar function.
Use array_map() with count as a callback to get the number of elements in each array, min() to get the smallest value. Then, to get the key of the smallest array - use array_flip() to flip the arrays keys and values, and access the $minth index. Now you can use the key to get the array you need:
$counts = array_map('count', $arr);
$min = min($counts);
$key = array_flip($counts)[$min];
$smallest_arr = $arr[$key];
Demo
Map your array to another array with counts of each child array. Get the key of the minimum value in this new array. Smallest array has the key of the minimum value:
$count = array_map('count', $arr);
$min = array_keys($count , min($count))[0];
var_dump($arr[$min]); // Array ( [0] => dogs [1] => cats )
Eval.in
a question about getting three random words out of a big string of say 200 words:
$trans = __("water paradise, chicken wing, banana beach, tree trunk")?>
// $trans becomes "water paradijs, kippenvleugel, bananen strand, boom tak"
// elements are separated by comma's and a space
Now imagine I want to get 5 random elements from that $trans string and echo that.
How can I do that? Code is welcome! Please keep this syntax in your answer:
$trans = the original string
$shufl = selective shuffle of 5 elements
contains e.g kippenvleugel, boom tak
You can do this by creating an array of strings using split, and then shuffling it with shuffle:
# Split the string into different elements
$strings = split(',', $trans);
# Shuffle the array
shuffle($strings);
# Select 5 elements
$shufl = array_slice($strings, 0, 5);
array_slice is then used to get the first 5 elements of the shuffled array. Another possibility is to use array_rand on the split array:
$shufl = array_rand(array_flip($strings), 5);
$array = explode ( ',',$trans);
shuffle($array);
for ( $i = 0 ; $i < 5 ; $i ++ ){
$shufl[] = $array[$i];
}
This will result in a $shufl array containing your 5 random elements.
Hope this helps :)
For better understanding. What is a random string?
Can it be:
'water paradijs' 'kippenvleugel' 'bananen strand'
or can it also be
'water strand' 'kippenvleugel bananen', etc.
?
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