• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Ternary Operator Basics
#1
"Sorry for the bad English, I'm using the translator to do this tutorial."



- What is a ternary operator?



In various situations in programming we need to deal with various scenarios, through conditional structures, such as if, else and switch. However, in some situations we deal with wave situations there are only 2 possible returns.



For example, let's imagine a hypothetical situation, in which if the player is an administrator he wins $ 1500, otherwise he will win $ 500.

We can do this logic using the if and else operator:



PHP Code:
if (PlayerData[playerid][pAdmin] > 0)

{? ? ? ? ? 

? ? 
GivePlayerMoney(playerid1500);





else

{

? ? 
GivePlayerMoney(playerid500);





Now notice that we are making a relatively long structure for a simple action, with only two possibilities. Is there no other way to write this code in a simpler way? Yes, there is, and that is what the ternary operator is for:



PHP Code:
GivePlayerMoney(playerid, (PlayerData[playerid][pAdmin] > 1500 500)); 



Now we did the same action with just one line of code, however let's understand a little bit about how to build a ternary operator.



- How to build a ternary operator?



Building a ternary operator is simple, its own structure is self-explanatory.



PHP Code:
(condition value if true value if false



To better understand, we can see that the '?' acts as an if and the ':' acts as the else.



- In what situations will I use the ternary operator?



This is a relative question, it depends a lot on the type of logic that you will build for your system, but as stated in the first question we will use the ternary operator for situations in which there are only 2 possibilities of return. Remembering that the ternary operator is not limited to returning only number values, but can also return strings and other options.



Example of a string with a ternary operator:



PHP Code:
SendClientMessage(playerid, -1, (playerData[playerid][pAdmin] > "True" "false")); 



- Problems with ternary operator



The main problem with the ternary operator is its structure, which because it is very compact, its structure can be difficult to read by programmers who are not used to it.



- End



This is my first personal authoring tutorial, i hope you like it and criticism will always be welcome!
  Reply


Messages In This Thread
Ternary Operator Basics - by RhaegarX - 2021-01-20, 07:29 PM
RE: Ternary Operator Basics - by Shadow - 2021-04-28, 07:58 AM
RE: Ternary Operator Basics - by RhaegarX - 2021-04-30, 12:22 AM
RE: Ternary Operator Basics - by kemper - 2021-04-30, 06:11 PM
RE: Ternary Operator Basics - by Shadow - 2021-05-03, 02:40 PM

Forum Jump: