Name
Name

Reputation: 408

How to use if/else inside array?

This is my following code:

$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')
                    }
);

Is there is a way to do that if conditional?

Upvotes: 1

Views: 80

Answers (3)

RJParikh
RJParikh

Reputation: 4166

Just need to append it in existing array like:

$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');
}

Check Live Demo: Click Here

Upvotes: 2

lazyCoder
lazyCoder

Reputation: 2561

@Reynald Henryleo you can do it like below:

<?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');
    }

Upvotes: 1

Drewby
Drewby

Reputation: 373

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

PHP docs reference.

Upvotes: 0

Related Questions