About meDashed CMS RSS
Kuragramming of beard
 
 
 /Root/Articles/

The ternary operator "?"

20.10.2011 21:04:08

This is the first article about PHP programming on this site so do not kick for the theme.

Today I will write about the ternary operator "?:" available in languages ​​like C whom belong to PHP and JavaScript .

So what is the ternary operator?

This is a simplified

if {} else {} for use in the rows. When using it "if" is not written, immediately put the comparison, but instead of the first bracket "{" question mark "?", the "} else {" is replaced by a colon ":".

Now I will give examples where this can be used ...

I like to get $ _POST or $ _GET variable it will look like so:

$ do = isset ($ _GET ['do'])? $ _GET ['do']: '';

replaces a line like

if (isset ($ _GET ['do'])){$ do = $ _GET [' do ']} else {$ do ='';}

true because a lot easier?!

This construction when copying and pasting to another variable reduces the number of edits on a single value.

Here is a more complex example, imagine that you are doing a multilingual site and do not want to produce a variety of templates for this you need to remove the words in different languages through PHP

This design replaces:

switch ($ lang) {

case "en": echo "English"; break;

 case "kz": echo "Kazakh"; break; 

default: echo "Default"; break;

}

?>

course so much less code will be, but I think it's worth noting that the use of several ternary operators in a row fraught with poor readability of code, so do not abuse it, strictly speaking, in its opinion in the second example I have abused them:) and if the language was would be more then certainly, but in my way is better than switch () {case: break;} to use!

What style of code you use to decide, but know better than all the variations of!

Good luck!

Рейтинг $r-- [1] $r++

Показать коментарии (vkontakte.ru)
}