普通网友 2014-10-23 14:25
浏览 12
已采纳

PHP中数组中的条件

I have a great couple of variables named $value1, $value2 etc. I want to create an array key for each variable only if the variable is not empty. Something like this:

$array = array(
    If (!empty($value1)) { "bar" => "foo", }
    If (!empty($value2)) { "foo" => "bar", }
);

How do I do this and what would be good practice?

  • 写回答

3条回答 默认 最新

  • dqqfuth6736 2014-10-23 14:29
    关注

    PHP arrays are dynamic, so you can add stuff to it easily:

    $array = array(); // start with empty one
    
    if (!empty($value1)) $array['bar'] = 'foo';
    if (!empty($value2)) $array['foo'] = 'bar';
    
    // you don't even have to specify a key, 
    // it will just increment accordingly if left out
    if (!empty($value3)) $array[] = 'foobar';
    

    this will result in (if all 3 vars are non-empty):

    array(3) {
      'a' => 'foo',
      'b' => 'bar',
      0   => 'foobar'
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度