I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
You can also do just:
$k = array_rand($array);
$v = $array[$k];
This is the way to do it when you have an associative array.
PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php
$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
$value = $array[array_rand($array)];
You can use mt_rand()
$random = $ran[mt_rand(0, count($ran) - 1)];
This comes in handy as a function as well if you need the value
function random_value($array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
return isset($array[$k])? $array[$k]: $default;
}
You could use the array_rand function to select a random key from your array like below.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];
or you could use the rand and count functions to select a random index.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];
Derived from Laravel Collection::random():
function array_random($array, $amount = 1)
{
$keys = array_rand($array, $amount);
if ($amount == 1) {
return $array[$keys];
}
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
Usage:
$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];
array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']
A few notes:
$amount has to be less than or equal to count($array).
array_rand() doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Use shuffle() afterwards if needed.
Documentation: array_rand(), shuffle()
edit: The Laravel function has noticeably grown since then, see Laravel 5.4's Arr::random(). Here is something more elaborate, derived from the grown-up Laravel function:
function array_random($array, $number = null)
{
$requested = ($number === null) ? 1 : $number;
$count = count($array);
if ($requested > $count) {
throw new \RangeException(
"You requested {$requested} items, but there are only {$count} items available."
);
}
if ($number === null) {
return $array[array_rand($array)];
}
if ((int) $number === 0) {
return [];
}
$keys = (array) array_rand($array, $number);
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
A few highlights:
Throw exception if there are not enough items available
array_random($array, 1) returns an array of one item (#19826)
Support value "0" for the number of items (#20439)
The array_rand function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:
$myArray = array(1, 2, 3, 4, 5);
// Random shuffle
shuffle($myArray);
// First element is random now
$randomValue = $myArray[0];
Another approach through flipping array to get direct value.
Snippet
$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));
array_rand return key not value. So, we're flipping value as key.
Note:
PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.
$rand = rand(1,4);
or, for arrays specifically:
$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
On-liner:
echo $array[array_rand($array,1)]
In my case, I have to get 2 values what are objects. I share this simple solution.
$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));
One line: $ran[rand(0, count($ran) - 1)]
I needed one line version for short array:
($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]
or if array is fixed:
[1, 2, 3, 4][mt_rand(0, 3]
Does your selection have any security implications? If so, use random_int() and array_keys(). (random_bytes() is PHP 7 only, but there is a polyfill for PHP 5).
function random_index(array $source)
{
$max = count($source) - 1;
$r = random_int(0, $max);
$k = array_keys($source);
return $k[$r];
}
Usage:
$array = [
'apple' => 1234,
'boy' => 2345,
'cat' => 3456,
'dog' => 4567,
'echo' => 5678,
'fortune' => 6789
];
$i = random_index($array);
var_dump([$i, $array[$i]]);
Demo: https://3v4l.org/1joB1
Use rand() to get random number to echo random key. In ex: 0 - 3
$ran = array(1,2,3,4);
echo $ran[rand(0,3)];
This will work nicely with in-line arrays. Plus, I think things are tidier and more reusable when wrapped up in a function.
function array_rand_value($a) {
return $a[array_rand($a)];
}
Usage:
array_rand_value(array("a", "b", "c", "d"));
On PHP < 7.1.0, array_rand() uses rand(), so you wouldn't want to this function for anything related to security or cryptography. On PHP 7.1.0+, use this function without concern since rand() has been aliased to mt_rand().
I'm basing my answer off of #ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
if (isset($array[$k])) {
return $array[$k];
} else {
return $default;
}
}
For more context, see my question over at Passing/Returning references to object + changing object is not working
Get random values from an array.
function random($array)
{
/// Determine array is associative or not
$keys = array_keys($array);
$givenArrIsAssoc = array_keys($keys) !== $keys;
/// if array is not associative then return random element
if(!$givenArrIsAssoc){
return $array[array_rand($array)];
}
/// If array is associative then
$keys = array_rand($array, $number);
$results = [];
foreach ((array) $keys as $key) {
$results[] = $array[$key];
}
return $results;
}
mt_srand usage example
if one needs to pick a random row from a text but same all the time based on something
$rows = array_map('trim', explode("\n", $text));
mt_srand($item_id);
$row = $rows[rand(0, count($rows ) - 1)];
A simple way to getting Randdom value form Array.
$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)
now every time you will get different colors from Array.
You get a random number out of an array as follows:
$randomValue = $rand[array_rand($rand,1)];
Related
I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
You can also do just:
$k = array_rand($array);
$v = $array[$k];
This is the way to do it when you have an associative array.
PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php
$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
$value = $array[array_rand($array)];
You can use mt_rand()
$random = $ran[mt_rand(0, count($ran) - 1)];
This comes in handy as a function as well if you need the value
function random_value($array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
return isset($array[$k])? $array[$k]: $default;
}
You could use the array_rand function to select a random key from your array like below.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];
or you could use the rand and count functions to select a random index.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];
Derived from Laravel Collection::random():
function array_random($array, $amount = 1)
{
$keys = array_rand($array, $amount);
if ($amount == 1) {
return $array[$keys];
}
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
Usage:
$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];
array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']
A few notes:
$amount has to be less than or equal to count($array).
array_rand() doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Use shuffle() afterwards if needed.
Documentation: array_rand(), shuffle()
edit: The Laravel function has noticeably grown since then, see Laravel 5.4's Arr::random(). Here is something more elaborate, derived from the grown-up Laravel function:
function array_random($array, $number = null)
{
$requested = ($number === null) ? 1 : $number;
$count = count($array);
if ($requested > $count) {
throw new \RangeException(
"You requested {$requested} items, but there are only {$count} items available."
);
}
if ($number === null) {
return $array[array_rand($array)];
}
if ((int) $number === 0) {
return [];
}
$keys = (array) array_rand($array, $number);
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
A few highlights:
Throw exception if there are not enough items available
array_random($array, 1) returns an array of one item (#19826)
Support value "0" for the number of items (#20439)
The array_rand function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:
$myArray = array(1, 2, 3, 4, 5);
// Random shuffle
shuffle($myArray);
// First element is random now
$randomValue = $myArray[0];
Another approach through flipping array to get direct value.
Snippet
$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));
array_rand return key not value. So, we're flipping value as key.
Note:
PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.
$rand = rand(1,4);
or, for arrays specifically:
$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
On-liner:
echo $array[array_rand($array,1)]
In my case, I have to get 2 values what are objects. I share this simple solution.
$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));
One line: $ran[rand(0, count($ran) - 1)]
I needed one line version for short array:
($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]
or if array is fixed:
[1, 2, 3, 4][mt_rand(0, 3]
Does your selection have any security implications? If so, use random_int() and array_keys(). (random_bytes() is PHP 7 only, but there is a polyfill for PHP 5).
function random_index(array $source)
{
$max = count($source) - 1;
$r = random_int(0, $max);
$k = array_keys($source);
return $k[$r];
}
Usage:
$array = [
'apple' => 1234,
'boy' => 2345,
'cat' => 3456,
'dog' => 4567,
'echo' => 5678,
'fortune' => 6789
];
$i = random_index($array);
var_dump([$i, $array[$i]]);
Demo: https://3v4l.org/1joB1
Use rand() to get random number to echo random key. In ex: 0 - 3
$ran = array(1,2,3,4);
echo $ran[rand(0,3)];
This will work nicely with in-line arrays. Plus, I think things are tidier and more reusable when wrapped up in a function.
function array_rand_value($a) {
return $a[array_rand($a)];
}
Usage:
array_rand_value(array("a", "b", "c", "d"));
On PHP < 7.1.0, array_rand() uses rand(), so you wouldn't want to this function for anything related to security or cryptography. On PHP 7.1.0+, use this function without concern since rand() has been aliased to mt_rand().
I'm basing my answer off of #ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
if (isset($array[$k])) {
return $array[$k];
} else {
return $default;
}
}
For more context, see my question over at Passing/Returning references to object + changing object is not working
Get random values from an array.
function random($array)
{
/// Determine array is associative or not
$keys = array_keys($array);
$givenArrIsAssoc = array_keys($keys) !== $keys;
/// if array is not associative then return random element
if(!$givenArrIsAssoc){
return $array[array_rand($array)];
}
/// If array is associative then
$keys = array_rand($array, $number);
$results = [];
foreach ((array) $keys as $key) {
$results[] = $array[$key];
}
return $results;
}
mt_srand usage example
if one needs to pick a random row from a text but same all the time based on something
$rows = array_map('trim', explode("\n", $text));
mt_srand($item_id);
$row = $rows[rand(0, count($rows ) - 1)];
A simple way to getting Randdom value form Array.
$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)
now every time you will get different colors from Array.
You get a random number out of an array as follows:
$randomValue = $rand[array_rand($rand,1)];
$testArray = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
print_r (array_keys($testArray, array(1,3, "file2.png"))); // Works
print_r (array_keys($testArray, array(1,3))); // Does not work.
As shown in the code above, I'd like to be able to quickly find an array in a multidimensional array but only specify two of the values.
One way to do this is to filter the testArray down to those number of keys using array_map, then use array_search to get the key.
$testArray = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
$search = [1,3];
$filtered = array_map(function ($item) use ($search){
return array_slice($item, 0, count($search));
}, $testArray);
$key = array_search($search, $filtered);
if ($key !== false){
print_r($testArray[$key]);
} else {
echo 'not found';
}
You can filter the array by testing which ones contain the values by computing the intersection and then get those keys:
$keys = array_keys(array_filter($testArray,
function($v) {
return count(array_intersect([1,3], $v)) == 2;
}));
You can extend it with a search $s variable:
$s = [1,3];
$keys = array_keys(array_filter($testArray,
function($v) use($s) {
return count(array_intersect($s, $v)) == count($s);
}));
This will return the keys for any sub array that contains [1,3], [3,1] or even [3,"file2.png",1], order is irrelevant.
To check them in order:
$s = [1,3];
$keys = array_keys(array_filter($testArray,
function($v) use($s) {
return count(array_intersect_assoc($s, $v)) == count($s);
}));
Loop through your data and slice each triplet, taking the first two items, and compare these to your needle. Return the file given a match.
<?php
$data = array(
array(1, 2, "file1.png"),
array(1, 3, "file2.png"),
array(1, 4, "file3.png")
);
$get_file_from_coords = function(array $coords) use ($data) {
foreach($data as $v) {
if (array_slice($v, 0, 2) == $coords) {
return $v[2];
}
}
};
echo $get_file_from_coords([1, 3]);
Output:
file2.png
(Note: If you have more than one file associated with your co-ordinate pair you'll need to adapt the code to return an array of matches.)
You don't necessarily need to slice or do anything fancy here. You can just compare like so:
[$v[0], $v[1]] == $coords
Your array data
$testArray = [
[1, 2, 'file1.png'],
[1 ,3, 'file2.png'],
[1 ,4, 'file3.png']
];
Specify what your search match conditions into an array
$matching = [1, 3];
Loop through your array data to find matches using array_intersect_assoc() which compares values and keys between two arrays. Store the actual found key and its values into a new array.
foreach ($testArray as $index => $contents) {
if (array_intersect_assoc($matching, $contents) == $matching) {
$found[$index] = $contents;
}
}
Display the results
echo '<pre>';
!empty($found) ? print_r($found) : print_r('not found');
Is there an equivalent min() for the keys in an array?
Given the array:
$arr = array(300 => 'foo', 200 => 'bar');
How can I return the minimum key (200)?
Here's one approach, but I have to imagine there's an easier way.
function minKey($arr) {
$minKey = key($arr);
foreach ($arr as $k => $v) {
if ($k < $minKey) $minKey = $k;
}
return $minKey;
}
$arr = array(300 => 'foo', 200 => 'bar');
echo minKey($arr); // 200
Try this:
echo min(array_keys($arr));
Try with
echo min(array_keys($arr));
min() is a php function that will return the lowest value of a set. array_keys() is a function that will return all keys of an array. Combine them to obtain what you want.
If you want to learn more about this two functions, please take a look to min() php guide and array_keys() php guide
use array_search() php function.
array_search(min($arr), $arr);
above code will print 200 when you echo it.
For echoing the value of lowest key use below code,
echo $arr[array_search(min($arr), $arr)];
Live Demo
This also would be helpful for others,
<?php
//$arr = array(300 => 'foo', 200 => 'bar');
$arr = array("0"=>array('price'=>100),"1"=>array('price'=>50));
//here price = column name
echo minOfKey($arr, 'price');
function minOfKey($array, $key) {
if (!is_array($array) || count($array) == 0) return false;
$min = $array[0][$key];
foreach($array as $a) {
if($a[$key] < $min) {
$min = $a[$key];
}
}
return $min;
}
?>
$arr = array(
300 => 'foo', 200 => 'bar'
);
$arr2=array_search($arr , min($arr ));
echo $arr2;
This question already has answers here:
PHP: How to remove specific element from an array?
(22 answers)
PHP array delete by value (not key)
(20 answers)
Closed 1 year ago.
I need to remove array item with given value:
if (in_array($id, $items)) {
$items = array_flip($items);
unset($items[ $id ]);
$items = array_flip($items);
}
Could it be done in shorter (more efficient) way?
It can be accomplished with a simple one-liner.
Having this array:
$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');
You can do:
$arr = array_diff($arr, array('remove_me', 'remove_me_also'));
And the value of $arr will be:
array('nice_item', 'another_liked_item')
I am adding a second answer. I wrote a quick benchmarking script to try various methods here.
$arr = array(0 => 123456);
for($i = 1; $i < 500000; $i++) {
$arr[$i] = rand(0,PHP_INT_MAX);
}
shuffle($arr);
$arr2 = $arr;
$arr3 = $arr;
/**
* Method 1 - array_search()
*/
$start = microtime(true);
while(($key = array_search(123456,$arr)) !== false) {
unset($arr[$key]);
}
echo count($arr). ' left, in '.(microtime(true) - $start).' seconds<BR>';
/**
* Method 2 - basic loop
*/
$start = microtime(true);
foreach($arr2 as $k => $v) {
if ($v == 123456) {
unset($arr2[$k]);
}
}
echo count($arr2). 'left, in '.(microtime(true) - $start).' seconds<BR>';
/**
* Method 3 - array_keys() with search parameter
*/
$start = microtime(true);
$keys = array_keys($arr3,123456);
foreach($keys as $k) {
unset($arr3[$k]);
}
echo count($arr3). 'left, in '.(microtime(true) - $start).' seconds<BR>';
The third method, array_keys() with the optional search parameter specified, seems to be by far the best method. Output example:
499999 left, in 0.090957164764404 seconds
499999left, in 0.43156313896179 seconds
499999left, in 0.028877019882202 seconds
Judging by this, the solution I would use then would be:
$keysToRemove = array_keys($items,$id);
foreach($keysToRemove as $k) {
unset($items[$k]);
}
How about:
if (($key = array_search($id, $items)) !== false) unset($items[$key]);
or for multiple values:
while(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
This would prevent key loss as well, which is a side effect of array_flip().
to remove $rm_val from $arr
unset($arr[array_search($rm_val, $arr)]);
The most powerful solution would be using array_filter, which allows you to define your own filtering function.
But some might say it's a bit overkill, in your situation...
A simple foreach loop to go trough the array and remove the item you don't want should be enough.
Something like this, in your case, should probably do the trick :
foreach ($items as $key => $value) {
if ($value == $id) {
unset($items[$key]);
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
}
Try array_search()
Your solutions only work if you have unique values in your array
See:
<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>
A better way would be unset with array_search, in a loop if neccessary.
w/o flip:
<?php
foreach ($items as $key => $value) {
if ($id === $value) {
unset($items[$key]);
}
}
function deleteValyeFromArray($array,$value)
{
foreach($array as $key=>$val)
{
if($val == $value)
{
unset($array[$key]);
}
}
return $array;
}
You can use array_splice function for this operation Ref : array_splice
array_splice($array, array_search(58, $array ), 1);
I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
You can also do just:
$k = array_rand($array);
$v = $array[$k];
This is the way to do it when you have an associative array.
PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php
$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
$value = $array[array_rand($array)];
You can use mt_rand()
$random = $ran[mt_rand(0, count($ran) - 1)];
This comes in handy as a function as well if you need the value
function random_value($array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
return isset($array[$k])? $array[$k]: $default;
}
You could use the array_rand function to select a random key from your array like below.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];
or you could use the rand and count functions to select a random index.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];
Derived from Laravel Collection::random():
function array_random($array, $amount = 1)
{
$keys = array_rand($array, $amount);
if ($amount == 1) {
return $array[$keys];
}
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
Usage:
$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];
array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']
A few notes:
$amount has to be less than or equal to count($array).
array_rand() doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Use shuffle() afterwards if needed.
Documentation: array_rand(), shuffle()
edit: The Laravel function has noticeably grown since then, see Laravel 5.4's Arr::random(). Here is something more elaborate, derived from the grown-up Laravel function:
function array_random($array, $number = null)
{
$requested = ($number === null) ? 1 : $number;
$count = count($array);
if ($requested > $count) {
throw new \RangeException(
"You requested {$requested} items, but there are only {$count} items available."
);
}
if ($number === null) {
return $array[array_rand($array)];
}
if ((int) $number === 0) {
return [];
}
$keys = (array) array_rand($array, $number);
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
A few highlights:
Throw exception if there are not enough items available
array_random($array, 1) returns an array of one item (#19826)
Support value "0" for the number of items (#20439)
The array_rand function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:
$myArray = array(1, 2, 3, 4, 5);
// Random shuffle
shuffle($myArray);
// First element is random now
$randomValue = $myArray[0];
Another approach through flipping array to get direct value.
Snippet
$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));
array_rand return key not value. So, we're flipping value as key.
Note:
PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.
$rand = rand(1,4);
or, for arrays specifically:
$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
On-liner:
echo $array[array_rand($array,1)]
In my case, I have to get 2 values what are objects. I share this simple solution.
$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));
One line: $ran[rand(0, count($ran) - 1)]
I needed one line version for short array:
($array = [1, 2, 3, 4])[mt_rand(0, count($array) - 1)]
or if array is fixed:
[1, 2, 3, 4][mt_rand(0, 3]
Does your selection have any security implications? If so, use random_int() and array_keys(). (random_bytes() is PHP 7 only, but there is a polyfill for PHP 5).
function random_index(array $source)
{
$max = count($source) - 1;
$r = random_int(0, $max);
$k = array_keys($source);
return $k[$r];
}
Usage:
$array = [
'apple' => 1234,
'boy' => 2345,
'cat' => 3456,
'dog' => 4567,
'echo' => 5678,
'fortune' => 6789
];
$i = random_index($array);
var_dump([$i, $array[$i]]);
Demo: https://3v4l.org/1joB1
Use rand() to get random number to echo random key. In ex: 0 - 3
$ran = array(1,2,3,4);
echo $ran[rand(0,3)];
This will work nicely with in-line arrays. Plus, I think things are tidier and more reusable when wrapped up in a function.
function array_rand_value($a) {
return $a[array_rand($a)];
}
Usage:
array_rand_value(array("a", "b", "c", "d"));
On PHP < 7.1.0, array_rand() uses rand(), so you wouldn't want to this function for anything related to security or cryptography. On PHP 7.1.0+, use this function without concern since rand() has been aliased to mt_rand().
I'm basing my answer off of #ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
if (isset($array[$k])) {
return $array[$k];
} else {
return $default;
}
}
For more context, see my question over at Passing/Returning references to object + changing object is not working
Get random values from an array.
function random($array)
{
/// Determine array is associative or not
$keys = array_keys($array);
$givenArrIsAssoc = array_keys($keys) !== $keys;
/// if array is not associative then return random element
if(!$givenArrIsAssoc){
return $array[array_rand($array)];
}
/// If array is associative then
$keys = array_rand($array, $number);
$results = [];
foreach ((array) $keys as $key) {
$results[] = $array[$key];
}
return $results;
}
mt_srand usage example
if one needs to pick a random row from a text but same all the time based on something
$rows = array_map('trim', explode("\n", $text));
mt_srand($item_id);
$row = $rows[rand(0, count($rows ) - 1)];
A simple way to getting Randdom value form Array.
$color_array =["red","green","blue","light_orange"];
$color_array[rand(0,3)
now every time you will get different colors from Array.
You get a random number out of an array as follows:
$randomValue = $rand[array_rand($rand,1)];