Sunday, 4 March 2018

php - Where can I read about conditionals done with "?" and ":" (colon)?






Possible Duplicate:
Reference - What does this symbol mean in PHP?







I've been doing conditionals with if/else or a year or so now. Looking at some new code, I'm seeing a conditional that appears to use ? and : instead of if and else. I'd like to learn more about this, but I am not sure what to google to find articles explaining how it works. How can I do it?


Answer



It's the Ternary Operator.



Basic usage is something like



$foo = (if this expressions returns true) ? (assign this value to $foo) : (otherwise, assign this value to $foo)


It can be used for more than assignment though, it looks like other examples are cropping up below.




I think the reason you see this in a lot of modern, OO style PHP is that without static typing you end up needing to be paranoid about the types in any particular variable, and a one line ternary is less cluttered than a 7 line if/else conditional.



Also, in deference to the comments and truth in naming, read all about the ternary operators in computer science.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...