doutuan4361 2017-03-21 14:17
浏览 62
已采纳

PHP:如何从数组foreach生成变量

Is it possible to generate variable names from array or list to avoid repetition? I am pulling item values from html form, this is the excerpt of code:

    $item1 = $item2 = $item3 = $item4 = "";


    if (isset($_GET["submit"])) {

        if (!empty($_GET["item1"])) { $item1 = htmlentities($_GET["item1"]);} else { $item1="*"; }
        if (!empty($_GET["item2"])) { $item2 = htmlentities($_GET["item2"]);} else { $item2="*"; } 
        if (!empty($_GET["item3"])) { $item3 = htmlentities($_GET["item3"]);} else { $item3="*"; } 
        if (!empty($_GET["item4"])) { $item4 = htmlentities($_GET["item4"]);} else { $item4="*"; } 

    }

Would it be possible to make array of items and generate the if block with foreach ?

  • 写回答

2条回答 默认 最新

  • douzhan8395 2017-03-21 14:22
    关注

    Consider saving the values in an array

    For the whole $_GET

    $items = [];  
    foreach($_GET as $key=>$val) {
        $items[$val] = !empty($val) ? htmlentities($val) : '*';
    }
    
    print_r($items);
    

    For some predefined elements in $elements

    $items = []; 
    $elements = array('item1','item2');
    
    foreach($elements as $val) {
        $items[$val] = !empty($_GET[$val]) ? htmlentities($_GET[$val]) : '*';
    }
    
    print_r($items);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 R语言 拟时序分析降维图如何减少分支
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统