Заполнить массив случайными числами php

rand

If called without the optional min , max arguments rand() returns a pseudo-random integer between 0 and getrandmax() . If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15) .

This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.

If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG .

Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

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() .

Parameters

The lowest value to return (default: 0)

The highest value to return (default: getrandmax() )

Return Values

A pseudo random value between min (or 0) and max (or getrandmax() , inclusive).

Changelog

Version Description
7.2.0 rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.
7.1.0 rand() has been made an alias of mt_rand() .
Читайте также:  Php basename without extension

Examples

Example #1 rand() example

The above example will output something similar to:

Источник

array_rand

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.

If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG .

Parameters

Specifies how many entries should be picked.

Return Values

When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. If multiple keys are returned, they will be returned in the order they were present in the original array. Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.

Changelog

Version Description
7.1.0 The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.

Examples

Example #1 array_rand() example

$input = array( «Neo» , «Morpheus» , «Trinity» , «Cypher» , «Tank» );
$rand_keys = array_rand ( $input , 2 );
echo $input [ $rand_keys [ 0 ]] . «\n» ;
echo $input [ $rand_keys [ 1 ]] . «\n» ;
?>

See Also

User Contributed Notes 7 notes

If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

It doesn’t explicitly say it in the documentation, but PHP won’t pick the same key twice in one call.

array_rand () takes a random value without ever being able to go back in its choice of random value.
A simple example:
I decide to mix an array of 10 entries to retrieve 3 values. This choice will give increasing and random values.

$pm = array_rand($myarray,3);
// $pm return array(0->0,1->6,2->8)

But if I decide to shuffle an array of 10 entries to get 10 entries, array_rand () will choose to assign a value to each return value and therefore the return array will not be random.

$gm = array_rand($myarray,count($myarray));
// $gm not random array(0->0,1->1,2->2,3->3,4->4,5->5,6->6,7->7,8->8,9->9)

The easiest way to have a truly random value:
either use array_rand () in a loop of 1 value at a time

——————
or simply use shuffle () to shuffle the array really randomly.

/**
* Wraps array_rand call with additional checks
*
* TLDR; not so radom as you’d wish.
*
* NOTICE: the closer you get to the input arrays length, for the n parameter, the output gets less random.
* e.g.: array_random($a, count($a)) == $a will yield true
* This, most certainly, has to do with the method used for making the array random (see other comments).
*
* @throws OutOfBoundsException – if n less than one or exceeds size of input array
*
* @param array $array – array to randomize
* @param int $n – how many elements to return
* @return array
*/
function array_random (array $array , int $n = 1 ): array
if ( $n < 1 || $n >count ( $array )) throw new OutOfBoundsException ();
>

return ( $n !== 1 )
? array_values ( array_intersect_key ( $array , array_flip ( array_rand ( $array , $n ))))
: array( $array [ array_rand ( $array )]);
>

// An example how to fetch multiple values from array_rand
$a = [ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’ , ‘g’ ];
$n = 3 ;

// If you want to fetch multiple values you can try this:
print_r ( array_intersect_key ( $a , array_flip ( array_rand ( $a , $n ) ) ) );

// If you want to re-index keys wrap the call in ‘array_values’:
print_r ( array_values ( array_intersect_key ( $a , array_flip ( array_rand ( $a , $n ) ) ) ) );

for a cryptographically secure version, try

/**
* fetch a random key from array, using a cryptograpically secure rng
* discussed+reviewed at https://codereview.stackexchange.com/questions/275832/cryptographically-secure-version-of-the-core-array-rand-function/
*
* @param array $array
* @throws ValueError if array is empty
* @return int|string key
*/
function array_rand_cryptographically_secure (array $array ) /*: int|string*/ $max = count ( $array ) — 1 ;
if ( $max < 0 ) throw new ValueError ( 'Argument #1 ($array) cannot be empty' );
>
return key ( array_slice ( $array , random_int ( 0 , $max ), 1 , true ) );
>

$tests = [
[ 5 , 6 , 7 ],
[ ‘a’ => 1 , ‘b’ => 2 , ‘c’ => 3 ],
[ ‘zero’ , 4 => ‘four’ , 9 => ‘nine’ ],
[ «PEAN» => 0 ],
[]];
foreach ( $tests as $test ) echo array_rand_cryptographically_secure ( $test ) . «\n» ;
>

?>
(this is an improved version, which unlike the first version, avoids copying *all* the keys)

Generate random index in weights array.
Implementation of Vose’s Alias Method.

class AliasMethod
protected $count ;
protected $prob ;
protected $alias ;

public function __construct ( $weight )
$count = count ( $weight );
$sum = array_sum ( $weight );
$d = $count / $sum ;
$small = [];
$large = [];

while (!empty( $small ) AND !empty( $large )) $l = array_pop ( $small );
$g = array_pop ( $large );
$prob [ $l ] = $weight [ $l ];
$alias [ $l ] = $g ;

if ( ( $weight [ $g ] += $weight [ $l ] — 1 ) < 1 )
$small [] = $g ;
else
$large [] = $g ;
>

foreach ( $large as $i )
$prob [ $i ] = 1 ;

foreach ( $small as $i )
$prob [ $i ] = 1 ;

$this -> prob = $prob ;
$this -> alias = $alias ;
$this -> count = $count ;

public function next (): int
$i = mt_rand ( 0 , $this -> count — 1 );
if ( mt_rand () / mt_getrandmax () prob [ $i ])
return $i ;
else
return $this -> alias [ $i ];
>
>

$weight = [ 1 , 2 , 1 , 1 , 100 , 1 , 1 , 5 , 1 , 1 ];
$rnd = new AliasMethod ( $weight );

$results = array_fill ( 0 , count ( $weight ), 0 );

for( $i = 0 ; $i < 100000 ; ++ $i ) $results [ $rnd -> next ()]++;
>
print_r ( $results );

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    Заполнить массив случайными числами (PHP)

    В PHP нет стандартной функции для генерации массива случайными числами. Самый простой способ написать функцию array array_fill_rand(int limit, [ min, max]) , которая принимает в качестве параметров: int limit — количество элементов массива и два необязательных параметра int min и int max — минимальное и максимальное значение элемента массива.

    Функция array_fill_rand()

    Напишем функцию array_fill_rand() и приведем пример использования.

    > else < for ($i=0; $i> return $array; > echo ‘

    '; // Массив из 5 элементов $rand_array = array_fill_rand(5); print_r($rand_array); // Массив из 10 элементов $rand_array = array_fill_rand(10); print_r($rand_array); // Массив из 5 элементов, со случайными числами в диапазоне от 0 до 10 $rand_array = array_fill_rand(5, 0, 10); print_r($rand_array); // Массив из 10 элементов, со случайными числами в диапазоне от -100 до 100 $rand_array = array_fill_rand(10, -100, 100); print_r($rand_array); echo '

    ‘; ?>

    В результате на экране появится 4 массива заполненные случайными числами, например:

    Array ( [0] => 12563 [1] => 24400 [2] => 9545 [3] => 20046 [4] => 19311 ) Array ( [0] => 8316 [1] => 19717 [2] => 346 [3] => 12171 [4] => 18536 [5] => 13441 [6] => 22822 [7] => 14695 [8] => 788 [9] => 6077 ) Array ( [0] => 8 [1] => 0 [2] => 5 [3] => 9 [4] => 8 ) Array ( [0] => 73 [1] => -49 [2] => -98 [3] => 83 [4] => -73 [5] => -57 [6] => 0 [7] => 37 [8] => 16 [9] => 40 )

    Категории

    Читайте также

    • Заполнить массив случайными числами (JavaScript)
    • Умножить массив на число (PHP)
    • Преобразовать массив в объект (PHP)
    • Цикл в обратном порядке (PHP)
    • Массив уникальных значений (JavaScript)
    • Ассоциативный массив в JavaScript
    • Как записать массив в файл (PHP)
    • Получить последнее значение массива (PHP)
    • Получить первое значение массива (PHP)
    • Массив в строку (JavaScript)
    • Получить массив ключей (PHP)
    • Сортировать числовой массив (JavaScript)

    Комментарии

    Автору статьи ставлю Like!.
    Описано все предельно ясно; без «лишней воды» так сказать. Несмотря на то что я начал изучать php совсем недавно все что описано выше мне понятно и функцию эту я нахожу очень полезной и простой в понимании.
    Спасибо что выложил статью и тем самым поделился опытом. Так что мне теперь понятно как реализовать рандомное заполнение значений элементов массива, да еще и с ограничением допустимых мин и мах значений.

    Вход на сайт

    Введите данные указанные при регистрации:

    Социальные сети

    Вы можете быстро войти через социальные сети:

    Источник

    как создать массив и наполнить случайными числами? Циклы не использовать. php

    Создать массив нужной длины с помощью array_pad() . Функцией array_map() заполнить случайным rand() значением каждый элемент:

    function randarr( $N, $min = 0, $max = 100) < return array_map( function() use( $min, $max) < return rand( $min, $max); >, array_pad( [], $N, 0) ); > print_r( randarr(5)); print_r( randarr(5, 22, 24)); print_r( randarr(5, 0, 1E9)); /* Array ( [0] => 93 [1] => 83 [2] => 76 [3] => 12 [4] => 88 ) Array ( [0] => 24 [1] => 23 [2] => 22 [3] => 22 [4] => 24 ) Array ( [0] => 289735940 [1] => 435158592 [2] => 650113843 [3] => 744380869 [4] => 830975526 ) */ 
    $e = range(0,100);shuffle($e);var_dump($e); 

    Вам надо было почитать больше про функции php. range возвращает массив упорядоченных чисел от 0 до 100 (N) в данном случае

    получается массив случайных чисел.

    циклы там, конечно же, используются, но в реализациях функций. вот если бы вас попросили реализовать перемешивание массива без shuffle, было бы гораздо полезней для вас.

    если у вас это какое-то задание, вы можете — забавы ради — представить два варианта — выше и еще один, основанный на goto со счетчиком. goto не является циклом, поэтому вы можете создать пустой массив, сгенерировать случайное число в массив, увеличить счетчик, после того как счетчик достигнет N, прыгнуть дальше. Формальные требования выполнены, применено достаточно извращенное решение.

    в дополнение к извращенным решениям ниже, наверняка кто-нибудь придумает вариант с random_bytes или вызовом /dev/random

    Источник

Оцените статью