如何在数组中使用if语句?

时间:2018-12-22 19:33:34

标签: arrays symfony oop if-statement formbuilder

我尝试在数组中创建一个if语句:

  $formBuilder->add('getTimestamp', DateType::class, array(
              'widget' => 'single_text',
               if($target == "new"){
                  'data' => new \DateTime(),
                }
                'attr' => array('class' => 'form-control', 'style' => 'line-height: 20px;'), 'label' => $field['fieldName'],
               ));

但是我收到一条错误消息

  

(1/1)ParseError

     

语法错误,意外的'if'(T_IF),预期为')'

2 个答案:

答案 0 :(得分:2)

'data' => $target == 'new' ? new \DateTime() : ''

答案 1 :(得分:0)

问题是数组内部的if。这是无效的php语法。您可以将其移到外面。

$options = [
     'widget' => 'single_text',
     'attr' => array('class' => 'form-control', 'style' => 'line-height: 20px;'), 'label' => $field['fieldName'],
];
if($target == "new"){
    $options['data'] = new \DateTime();
}

$formBuilder->add('getTimestamp', DateType::class, $options);