随机问候生成器

试图让这个随机问候生成器工作。起初我没有 $greet 变量的数组,但他们收到错误消息说我没有定义变量。现在我收到一个数组到字符串的转换错误。有什么想法吗?


<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<title>hello</title>

</head>

<body>

<?php

//store random greetings


$greet = array('Hello','Welcome','Greetings!','Salutatons!','Good day!', 'Yo!');


switch($greet){


case 1: 

  $greet = 'Hello!'; 

  break;

  case 2: 

  $greet = 'Welcome!'; 

  break;

case 3: 

  $greet = 'Greetings!'; 

  break;

case 4: 

  $greet = 'Salutations!'; 

  break;

case 5: 

  $greet = 'Good day!'; 

  break;

case 6: 

 $greet = 'Yo!'; 

 break;

}

echo $greet;


//set the seed for mtrand with the number of microseconds

//since the last full second of the clock


mt_srand((double)microtime() * 1000000);

//computes a random integer 0-4


$number=mt_rand(0,5);

echo $number;

?>

</body>

</html>


守着星空守着你
浏览 147回答 1
1回答

梵蒂冈之花

您应该使用array_rand()从数组中获取随机键。不是开关/外壳。看看下面的代码。现在$greet变量将用数组中的随机问候覆盖自己。<?php//store random greetings$greet = array('Hello','Welcome','Greetings!','Salutatons!','Good day!', 'Yo!');$greet = $greet[array_rand($greet)];echo $greet;//set the seed for mtrand with the number of microseconds//since the last full second of the clockmt_srand((double)microtime() * 1000000);//computes a random integer 0-4$number=mt_rand(0,5);echo $number;
打开App,查看更多内容
随时随地看视频慕课网APP