dongtuoji5396 2015-08-14 22:34
浏览 33

PHP理解用于提取复选框值的小片段代码

I have a snippet of PHP code, it works but I was curious to know why.

Green: <input type="checkbox" name="color[]" value="green" />
Black: <input type="checkbox" name="color[]" value="black" />
White: <input type="checkbox" name="color[]" value="white" />
Blue:  <input type="checkbox" name="color[]" value="blue"  />
Red:   <input type="checkbox" name="color[]" value="red"   />

then here is what I don't get for this PHP code below, how is $colors an array, I thought you have to at least have $colors[] = $_POST['color'].

if (isset($_POST['color'])) {
  $colors = $_POST['color'];
}
echo $colors[0];

Thanks for helping me better understand this.

  • 写回答

2条回答 默认 最新

  • duadpnld426905 2015-08-14 22:36
    关注

    You don't need to explicitly add [] in PHP. Notice that you don't even need to define the type! This is PHP :)

    $_POST['color'] is an array, so $colors will also be!

    Read: http://www.html-form-guide.com/php-form/php-form-checkbox.html

    Edit

    In PHP, if you write $colors[] = $var, you are actually adding $var to the end of that array. If the array is empty, $colors[0] == $var.

    $colors = $_POST['color']; // $colors receives the array
    $colors[] = $_POST['color']; // $colors[0] receives the array, if $colors was empty
    

    More info: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了