note 110115 added to function.array-rand
| From: | BirkofffromPHPRomania.net | Date: | Fri, 21 Sep 2012 00:09:56 +0000 |
| Subject: | note 110115 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190938@lists.php.net to get a copy of this message | ||
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
*/
?>
----
Server IP: 69.147.83.199
Probable Submitter: 188.25.125.147
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- https://master.php.net/note/edit/110115
Del: integrated -- https://master.php.net/note/delete/110115/integrated
Del: useless -- https://master.php.net/note/delete/110115/useless
Del: bad code -- https://master.php.net/note/delete/110115/bad+code
Del: spam -- https://master.php.net/note/delete/110115/spam
Del: non-english -- https://master.php.net/note/delete/110115/non-english
Del: in docs -- https://master.php.net/note/delete/110115/in+docs
Del: other reasons-- https://master.php.net/note/delete/110115
Reject -- https://master.php.net/note/reject/110115
Search -- https://master.php.net/manage/user-notes.php