如何在数组中使用if / else?

时间:2017-03-27 05:21:00

标签: php codeigniter

这是我的以下代码:

$update = array(
                    'fullname' => $this->input->post('fullname'),
                    'phone' => $this->input->post('phone'),
                    'sex' => $this->input->post('sex'),
                    'city' => $this->input->post('city'),
                    if($_POST['bday']){ -->THIS FROM SUBMIT FORM
                        'bday' => $this->input->post('birthday')
                    }
);

如果有条件的话,有没有办法做到这一点?

3 个答案:

答案 0 :(得分:2)

只需将其附加到现有数组中,如:

$update = array(
 'fullname' => $this->input->post('fullname'),
 'phone' => $this->input->post('phone'),
 'sex' => $this->input->post('sex'),
 'city' => $this->input->post('city')                   
);

if($_POST['bday']){ 
    $update['bday'] = $this->input->post('birthday');
}

查看实时演示: Click Here

答案 1 :(得分:1)

@Reynald Henryleo你可以这样做:

<?php
    $update = array(
                    'fullname' => $this->input->post('fullname'),
                    'phone' => $this->input->post('phone'),
                    'sex' => $this->input->post('sex'),
                    'city' => $this->input->post('city'),
                    'bday' => !empty($_POST['bday']) ? $this->input->post('birthday') : null
            );

    // if you don't want bday with null value then try below one

    $update = array(
                    'fullname' => $this->input->post('fullname'),
                    'phone' => $this->input->post('phone'),
                    'sex' => $this->input->post('sex'),
                    'city' => $this->input->post('city')
            );
    if(!empty($_POST['bday'])){
        $update["bday"] = $this->input->post('birthday');
    }

答案 2 :(得分:0)

'city' => $this->input->post('city'),
'bday' => ($_POST['bday']) ? $this->input->post('birthday') : ''

PHP docs reference.