note 90644 added to function.array-rand
| From: | webmaster at askapache dot com | Date: | Sat, 02 May 2009 08:15:32 +0000 |
| Subject: | note 90644 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-154097@lists.php.net to get a copy of this message | ||
Quick Tips:
to use array_rand to display/return a random item from an array:
<?php
// Using array_rand
$a=array( 'one', 'two', 'three' );
echo $a[array_rand($a)]; // 'one' or 'two' or 'three'
// On associative arrays
$b=array( 'G'=>'Good', 'B'=>'BAD',
'O'=>'OK' );
echo array_rand($b); // 'G' or 'B' or 'O'
echo $b[array_rand($b)]; // 'Good' or 'BAD' or 'OK'
// Much nicer than these other methods that aren't pretty
$rand=rand(0,sizeof($a));
echo $a[$rand];
shuffle($a);
echo $a[0];
shuffle($b);
$r=array_values($b);
echo $r[rand(0,sizeof(array_keys($b)))];
?>
----
Server IP: 208.69.120.35
Probable Submitter: 24.123.215.60
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- https://master.php.net/note/edit/90644
Del: integrated -- https://master.php.net/note/delete/90644/integrated
Del: useless -- https://master.php.net/note/delete/90644/useless
Del: bad code -- https://master.php.net/note/delete/90644/bad+code
Del: spam -- https://master.php.net/note/delete/90644/spam
Del: non-english -- https://master.php.net/note/delete/90644/non-english
Del: in docs -- https://master.php.net/note/delete/90644/in+docs
Del: other reasons-- https://master.php.net/note/delete/90644
Reject -- https://master.php.net/note/reject/90644
Search -- https://master.php.net/manage/user-notes.php