Reputation: 781
My Picture:
In this picture i am saving group type using radio button.if balance sheet is selected it saved as "B" and profit and loss as "P".if without select anything,it save as "T".
Now my problem is i am using ternary operator to check conditions,but for me only 2nd conditions is working.It is not working for more than one conditions in that operator. How i resolve my problem.
public function GEntry()
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->form_validation->set_rules('gName', 'gName', 'required');
$this->form_validation->set_error_delimiters('<div class="text-danger">',
'</div>');
$check1 = isset($_POST['gType']);
$check = ($check1 == 'B') ? "B" : ($check1 == 'P') ? "P" :'T';
//$check1 = isset($_POST['tin_no1']) ? "Y" : "N";
if ($this->form_validation->run())
{
$data= array(
'gName' => $this->input->post('gName'),
'gType' => $check
);
//means insert a data into the table
$this->db->insert('groups',$data);
return redirect('Master/Groups');
}
Upvotes: 1
Views: 2657
Reputation: 446
You can capture an entire ternary operator with using brackets like this:
$a = ($b === 'A') ? 'A' : (($b === 'B') ? 'B' : (($b === 'C') ? 'C' : 'D'));
BUT ... i would not recommend you this procedure, if your decisioning takes more than 2-3 conditions. In that case, i would recommend you, to use a switch instead:
switch ($b)
{
case 'A':
$a = 'A';
break;
default:
$a = 'D';
break;
}
ALSO ... i would recommend you to use a ===
comparator instead of the ==
comparator like in the code provided by you. The third =
makes sure, that both of the given values are of the same data type, so you compare a string
with another string
in your example.
Upvotes: 0
Reputation: 1394
You are not assigning the post data to the variable $check1
. You are checking like this $check1 = isset($_POST['gType']);
this will give you true
/ false
.
Update like below:
$check1 = isset($_POST['gType']) && in_array($_POST['gType'], ['B', 'P']) ? $_POST['gType'] : 'T';
Then remove this line $check = ($check1 == 'B') ? "B" : ($check1 == 'P') ? "P" :'T';
Upvotes: 1