How to write a cleaner code for this piece of php snippet? I would like to know if there is a better/shorter/cleaner/resource saving method for this snippet of php code with codeigniter? Thanks.

$code = $this-&gt;uri-&gt;segment(3);

if (!$code) {
    // validation
    $this-&gt;form_validation-&gt;set_rules('code', 'PassCode', 'required|trim|max_length[100]|xss_clean');

    // run validation to check if validation rules are satifised
    if ($this-&gt;form_validation-&gt;run() == true) {
        $code = $this-&gt;input-&gt;post('code');
        $user_id = $this-&gt;user_model-&gt;getUserId($code);
        if (empty($user_id)) {
            $data['errorMessage'] = 'Your code is not valid.';
        } else {
            redirect('user/profile');   
        }
    }
} else {
    $user_id = $this-&gt;user_model-&gt;getUserId($code);
    if (empty($user_id)) {
        $data['errorMessage'] = 'Your code is not valid.';
    } else {
        redirect('user/profile');   
    }
}
if ($this-&gt;form_validation-&gt;run() == true)


is redundant, just use...

if ($this-&gt;form_validation-&gt;run())




Also, you can move the whole if (empty($user_id)) block outside to the end to avoid duplicating it:

$code = $this-&gt;uri-&gt;segment(3);

if (!$code) {
    // validation
    $this-&gt;form_validation-&gt;set_rules('code', 'PassCode',
        'required|trim|max_length[100]|xss_clean');

    // run validation to check if validation rules are satifised
    if ($this-&gt;form_validation-&gt;run()) {
        $code = $this-&gt;input-&gt;post('code');
        $user_id = $this-&gt;user_model-&gt;getUserId($code);
    }
} else {
    $user_id = $this-&gt;user_model-&gt;getUserId($code);
}

if (empty($user_id)) {
    $data['errorMessage'] = 'Your code is not valid.';
} else {
    redirect('user/profile');   
}