Ternary operator, switch or if else, which is simpler?

Introduction:

In the process of developing a project, when a conditional operator needs to be used, Xiaobai prefers if else or switch, and the big guys generally consider using the ternary operator first, because the ternary operator can be done with just one line of code, code block It also looks more refreshing.

The wording of switch:

switch ((int)$type) {
	case 1:
		$typeName = '支付宝';
		break;
	case 2:
		$typeName = 'QQ钱包';
		break;
	case 3:
		$typeName = '微信支付';
		break;
}

The writing of if else:

if((int)$type==1){
    $typeName = '支付宝';
}else if((int)$type==2){
    $typeName = 'QQ钱包';
}else{
    $typeName = '微信支付';
}

Ternary operator:

Ternary operator, also known as the conditional operator, which is the only three operands operators, it sometimes called ternary operator . Generally speaking, the associativity of ternary operators is right associative.

grammar:

Expression ( condition)? Result 1: Result 2 

The meaning of the ? Operator is: first evaluate the value of the expression, if it is true (the condition is true), it is result 1; if the value of the expression is false, it is result 2.

$typeName = (int)$type==1 ? '支付宝' : ( (int)$type==2 ? 'QQ钱包' : '微信支付' );

Such a simple ternary operator, have you discarded it~-~

Guess you like

Origin blog.csdn.net/qq15577969/article/details/114165941