2012-02-23 123 views
2

是否有一种更优雅或更高效的随机选择列表中字符串的方法?随机化字符串选择

$case = rand(1,4); 
    switch ($case) { 
     case 1: $message = "Check this out."; 
     break; 
     case 2: $message = "Dig this."; 
     break; 
     case 3: $message = "Listen to this."; 
     break; 
     case 4: $message = "Try out this."; 
     break; 
    } 
+1

把消息字符串数组,然后你可以用代码 – 2012-02-23 19:28:10

回答

6

array_rand()

$messages = array(
    "Check this out.", 
    "Dig this.", 
    "Listen to this.", 
    "Try out this." 
); 

$message = $messages[array_rand($messages)]; 
+0

一行做到这一点值得一提的是'array_rand()'返回一个随机数组的键,而不是随机数组值... – Andrew 2012-02-24 19:42:46