Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_rand function

With the PHP function array_rand, we can obtain one or more random keys from the provided array

Description / Descripción
array_rand(array $array, int $num = 1): int|string|array

Parameters

$array – The array you provide.

$num – Specifies how many keys it will take from the provided array.

Returns

When we specify that we want a single entry with $num, array_rand will return a random key, which can be an integer or a string depending on the type of key.

When we specify $num greater than 1 ($num > 1), array_rand will return an array with the keys. These keys will be returned in the order they appear in the original array.

Trying to obtain more elements than an array has will result in an E_WARNING error and a return value of null. This happens when $num > count($array).

Example

$marcasDeAutos = array(
    "Toyota",
    "Ford",
    "Honda",
    "Chevrolet",
    "Volkswagen",
    "BMW",
    "Mercedes-Benz",
    "Audi",
    "Nissan",
    "Hyundai",
    "Kia",
    "Subaru",
    "Mazda",
    "Lexus",
    "Jeep",
);

print_r(array_rand($marcasDeAutos,2));
Array
(
    [0] => 2
    [1] => 10
)
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category