NOVINKA: Najžiadanejšie rekvalifikačné kurzy teraz s 50% zľavou + kurz AI ZADARMO. Nečakaj, táto ponuka dlho nevydrží! Zisti viac:

PHP - array_rand

Trieda

Koreň \ Bez triedy

Metóda - array_rand

(PHP 4, PHP 5, PHP 7)

Selects a given number of random items in a given array and returns the keys of these items.

Note: This function uses a pseudo-random number generator and therefore is not suited for cryptographic use.

Procedurálne

  • function array_rand (array $array, int $num = 1) : mixed

Parametre

NázovDátový typPredvolená hodnotaPopis
$arrayarray

The input array, from which the random keys will be selected.

$numint 1

The number of keys, which should be selected.

Mávratovej hodnoty

Vracia: mixed

If the value 1 is passed as the $num parameter, only the randomly-selected key itself will be returned.

In case of passing a value greater than 1 as the $num parameter, an array containing the randomly-selected keys will be returned.

An attempt to select more keys than items in the given array will result in returning null and generating E_WARNING.

Príklady

This example picks 2 random keys from an array, outputs these keys and the corresponding values:

<?php

$in = array('key1' => '1st item', 'key2' => '2nd item', 'key3' => '3rd item', 'key4' => '4th item');
$randKeys = array_rand($in, 2);

foreach($randKeys as $key){
    $value = $in[$key];
    echo "$key => $value" .  PHP_EOL;
}

Súvisiace manuály

      • function shuffle (array &$array) : bool
      Aktivity