Thursday, September 15, 2005

Ternary Operator

The lesson for today is on the Ternary operator. Examples are in PHP.
The ternary operator is a very useful tool for simplifying or cleaning up your code. The structure of the ternary operator is similar to an "if then else" statement, but it is an actual operator which enacts on a boolean data type, so it is typically faster. Unlike most operators it has three members and a result instead of two members and a result(ie. '+' has two members, the two things you are adding together, and the result). One common symbol for the ternary operator is '? :'. The first member is the conditional. This typically takes the form of a boolean expression such as ($result == 0). This is a boolean expression because it has two possible results, true or false. The second member is the response. The result of the operation will equal the response if the conditional is true. The third member is the alternate response. The result of the operation will equal the alternate response if the conditional is false. Using the ternary operator the following code:
if ($string == '') {
$integer = '0';
} else {
$integer = $string;
}
which can be used to replace a zero length string with the number 0 can be written as:
$integer = ($string == '')?0:$string;
This significantly shortens the length of our code. This example is mainly useful when trying to handle strings like they are integers without actually converting them to integers.


News for today.
Yoda's training continues to go well, although he does not want to go to the kennel at all. I have to force him in everytime I have to leave my house. He also did not want to listen to my mom yesterday when I got home. She let him out because I got home and he was asking to go out, but I was trying to eat so I couldn't let him out myself. If he continues to not listen to her, I might get her involved in his training to see if that helps. He also is completely obsessed with my guinea pig, perl, and not in a good way. He attacks her cage, and on numerous occasions he has almost knocked it off it's stand. Hopefully this is just a phase because she is something new, because it will be very hard to keep Yoda separate from Perl. Tonight I will continue his training, and if he continues to do so well, then this weekend I will be taking him to Pet Supplies Plus to practice being in public, but not as distracting as PetSmart. While there I will let him pick out a new chew toy.

No comments: