设置关联数组时出错

时间:2014-12-12 04:29:00

标签: php arrays

我试图展示动物和平均寿命多年,它不会显示生命。有什么帮助吗?

<?php
$animal = $_POST['animal'];

array(
$lifespans["Mouse"] => "4",
$lifespans["Queen Bee"] => "5",
$lifespans["Squirrel"] => "20",
$lifespans["Rattlesnake"] => "22",
$lifespans["Pheasant"] => "27",
$lifespans["Mallard Duck"] => "29",
$lifespans["Bear"] => "40",
$lifespans["Box Turtle"] => "123",
);

print("<p>The $animal has an average life space of $lifespans years.</p>");

&GT;

编辑:

用户有一个这些动物的下拉菜单,当他们选择一个并点击提交时,它将显示他们的生命周期。

1 个答案:

答案 0 :(得分:4)

修复你的数组声明:

$lifespans = array(
    "Mouse" => "4", // You could also do "Mouse" => 4, etc. as PHP will type-juggle
    "Queen Bee" => "5",
    "Squirrel" => "20",
    "Rattlesnake" => "22",
    "Pheasant" => "27",
    "Mallard Duck" => "29",
    "Bear" => "40",
    "Box Turtle" => "123",
);

使用它来访问数组的特定元素:

print("<p>The $animal has an average life space of $lifespans[$animal] years.</p>");

我是字符串连接的更大粉丝:

print("<p>The " . $animal . " has an average life space of " . $lifespans[$animal] . " years.</p>");