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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c