duan1933 2014-10-20 01:28
浏览 23
已采纳

php表单下拉菜单正常工作,但在进入函数时却没有

I'm currently going through a PHP tutorial and created a form drop down menu. I'm trying to make my code more efficient by moving some of the blocks of code into functions.

Why does the following code not work when making it a function (example 1) but it does work otherwise (example 2)?

Example 1:

<div id="leftnav">
<div class="search">

    <form name="search" method="get" action="search.html" id="search">
        <input type="text" value="keywords" name="keyword" class="s0" /> 
        <br />

        <select name="title" class="s2">

        <?php 

            productSelection(); // This is the function I am referring to

        ?> 


        </select>
        <br />
        <input type="submit" name="search" value="Search Products" class="button marT5" />
        <input type="hidden" name="page" value="search" />
    </form>

The function is defined as followed:

productSelection() {

sort($titles, SORT_STRING); // Sort array of products

foreach ($titles as $deserts) {

    printf("<option value=\"%s\">%s</option>", $deserts, $deserts);

}

Example 2:

    <form name="search" method="get" action="search.html" id="search">
        <input type="text" value="keywords" name="keyword" class="s0" /> 
        <br />

        <select name="title" class="s2">

        <?php 

            sort($titles, SORT_STRING); // Sort array of products

            foreach ($titles as $deserts) {

                printf("<option value=\"%s\">%s</option>", $deserts, $deserts);

            } 

        ?> 


        </select>
        <br />
        <input type="submit" name="search" value="Search Products" class="button marT5" />
        <input type="hidden" name="page" value="search" />
    </form>
  • 写回答

1条回答 默认 最新

  • dqssst0144 2014-10-20 01:30
    关注

    $titles is not available to your function because it is out of scope. Global variables are not available inside of functions unless you pass them as parameters (preferred) or use the global keyword (not recommended).

    productSelection($titles) {
        sort($titles, SORT_STRING); // Sort array of products
        foreach ($titles as $deserts) {    
            printf("<option value=\"%s\">%s</option>", $deserts, $deserts);
        }
    }
    

    And when invoking it:

    <?php 
        productSelection($titles); 
    ?> 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?