PHP array_rand Function | Pick Random Keys From Array

PHP array_rand is an inbuilt Function in PHP. It is used to pick one or more random keys from an array. On a practical basis, this is not that useful because the function uses a pseudo-random number generator that is not suitable for cryptographic purposes. In this article, we will discuss the PHP array_rand Function. Also, we will discuss a few examples of using it.

Syntax

array_rand($array, $numberOfElements = 1)

Parameters

The PHP array_rand Function expects two parameters. One parameter is mandatory while the other is optional. The description of the parameters is as follows:

  • $array: The first parameter is a mandatory array which refers to the original input array.
  • $numberOfElements: The second parameter is an optional integer which refers to the number of random elements. The default value of this parameter is 1. It should be greater than or equal to 1 or the function throws E_WARNING.

Return Value

On picking only one random element, the array_rand Function returns the key for a random value. However, if the number of elements are more than 1 then it returns an array of keys of the random values. While picking elements more than the number of elements in the array, it returns NULL along with E_WARNING error.

PHP array_rand Function Diagram

Examples

Let’s discuss a few examples of using the array_rand Function in PHP.

Example 1: Single Random Key

For instance, consider an example to get a single random key.

<?php

	$testArray = array(
		'a' => 'apple',
		'b' => 'ball',
		'c' => 'cat',
		'd' => 'dog'
	);
	$rand = array_rand($testArray);
	print_r($rand);
	/* b */

	print_r($testArray[$rand]);
	/* ball */

?>

By default, the function returns a single random key when the numberOfElements parameter is not passed.

Example 2: More Than One Random Key

On passing the numberOfElements parameter greater than 1, the function returns an array of random keys.

<?php

	$testArray = array(
		'a' => 'apple',
		'b' => 'ball',
		'c' => 'cat',
		'd' => 'dog'
	);
	$rand = array_rand($testArray, 3);
	print_r($rand);
	/*
	Array
	(
	    [0] => a
	    [1] => b
	    [2] => d
	)
	*/

?>

Example 3: Error Response

<?php

	$testArray = array(
		'a' => 'apple',
		'b' => 'ball',
		'c' => 'cat',
		'd' => 'dog'
	);
	$rand = array_rand($testArray, 5);
	var_dump($rand);
	/*  NULL  */

?>

If the numberOfElements parameter is more than the number of elements in the array, the function returns NULL.

Conclusion

In the above article, we discussed the PHP array_rand Function. You can read more about it on the Official Documentation of PHP. Also, you can learn about more Array Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *