从PHP数组返回值

时间:2014-10-26 23:30:55

标签: php arrays

<?php
  $change=.07;
  $coins=array(
".01"=>"1 Penny",
".02"=>"2 Pennys",
".03"=>"3 Pennys",
".04"=>"4 Pennys",
".05"=>"5 Pennys",
".06"=>"6 Pennys",
".07"=>"7 Pennys",
".08"=>"8 pennys",
".09"=>"9 Pennys",
".10"=>"1 Dime",
".11"=>"1 Dimes and 1 Penny",
".12"=>"1 Dime and 2 Pennys",
".13"=>"1 Dime and 3 Pennys",
".14"=>"1 Dime and 4 Pennys",
".15"=>"1 Dime and 5 Pennys",
".16"=>"1 Dime and 6 Pennys",
".17"=>"1 Dime and 7 Pennys", 
".18"=>"1 Dime and 8 Pennys",
".19"=>"1 Dime and 9 Pennys",
".20"=>"2 Dimes",
".21"=>"2 Dimes and 1 Penny",
".22"=>"2 Dimes and 2 Pennys",
".23"=>"2 Dimes and 3 pennys",
".24"=>"2 Dimes and 4 Penny",
".25"=>"1 Quarter",
".26"=>"1 Quarter and 1 Penny",
".27"=>"1 Quarter 2 Pennys",
".28"=>"1 Quarter 3 Pennys",
".29"=>"1 Quarter and 4 Pennys",
".30"=>"1 Quarter and 5 Pennys",
".31"=>"1 Quarter and 6 Pennys",
".32"=>"1 Quarter and 7 Pennys",
".33"=>"1 Quarter and 8 Pennys",
".34"=>"1 Quarter and 9 Pennys",
".35"=>"1 Quarter and 1 Dime",
  );
  ?>

如何将$ change显示为数组的第二个值。因此,如果$ change是.25我会希望它打印“1 Quarter”。另外在我的实际代码中,$每次运行时都会更改。

2 个答案:

答案 0 :(得分:1)

使用方括号语法as described in the manual

访问数组的特定元素
echo $coins[$change];

答案 1 :(得分:0)

试试这个

foreach($coins as $index => $value){
   if($index == $change){
     print $value;
   }
}

这是工作代码

http://ideone.com/gtKIIz