note 110115 deleted from function.array-rand by googleguy
| From: | googleguy@php.net | Date: | Fri, 21 Sep 2012 02:08:21 +0000 |
| Subject: | note 110115 deleted from function.array-rand by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190940@lists.php.net to get a copy of this message | ||
Note Submitter: Birkoff from PHPRomania.net
----
Example of using array_rand with maintaining keys and values.
<?php
// your array look like this
$test = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
'key4' => 'value4',
'key5' => 'value5' ) ;
// set max number of random elements you want
$y = $max = 3;
for($x = 1; $x<=$y; $x++) {
$k = array_rand($test, 1);
// because we can get a key already chosen, check how many I have
$rand_keys[$k] = $k;
if ( count($rand_keys) < $max ) {
// If not have the maximum number of our interest, increase the number of loops
$y++;
} else { // get out of the loop
break;
}
}
// shows what he chose.
foreach($rand_keys as $k) {
echo 'key: '.$k.' - value: '.$test[$k] ."\r\n";
}
/*
key: key5 - value: value5
key: key1 - value: value1
key: key3 - value: value3
*/
?>