I have a piece of code and I want to convert it to ternary operator. Can anyone help? It has 1 if and 2 else if conditions so I am having trouble converting it. Here is my code.
if ($this->session->data['desired_service']==1){
echo 'Home Delivery';
} else if ($this->session->data['desired_service']==2){
echo 'Take Away';
} else if ($this->session->data['desired_service']==3){
echo 'DinIN';
}
Here is the code that I have used so far.
$service = ( $this->session->data['desired_service']== 1 ) ? "Home Delivery" : ( $this->session->data['desired_service'] == 2 ) ? "Take Away" : ( $this->session->data['desired_service'] == 3 ) ? "DinIN";
But it is giving me a syntax error.
echo ($this->session->data['desired_service'] == 3) ? 'DinIN' : (($this->session->data['desired_service']==1) ? 'Home Delivery' : ($this->session->data['desired_service'] == 2) ? 'Take Away' : '');
Explanation:
Use nested ternary operator.
If variable equal to 3, print 'DinIN'
else : two cases:
if 1 : Home Delivery
else : Take Away
Demos:
Another solution
Use predefined array:
Get all your options in an array and add
1,2 and 3 as keys.
Check array with isset
and the variable.
If it is set, print it, else blank.
Purpose solved.
<?php
$arr = array();
$arr[1] = 'Home Delivery';
$arr[2] = 'Take Away';
$arr[3] = 'DinIN';
echo isset($arr[$this->session->data['desired_service']]) ? $arr[$this->session->data['desired_service']] : '';
?>
This is not a good example of when to use ternary operators. Personally, looking at your data - I would use a switch statement, as it will be easier to read and add more options to.
switch($this->session->data['desired_service']){
case '1':
$service = "Home Delivery";
break;
case '2':
$service = "Take Away";
break;
case '3':
$service = "DinIN";
break;
}