Jump to content

Check out our Community Blogs

- - - - -

PHP6 - ifsetor() :?

Posted by John, 16 February 2009 · 1133 views

Web developers are constantly validating data, either through JavaScript or through a server side programming language such as PHP. If you have done any PHP development, I am sure you have been in the situation where, if a request variable is set, you want want to use that value, if it is not set, you would like it to default to a specific value. The most common and logical method to accomplish this is to use an if/else block.
if(isset($_GET['foo'])) {
$bar = $_GET['foo'];
} else {
$bar = 1;

The other, more dense, and in my opinion, more elegant option is to use the ternary operator.
$bar = (isset($_GET['foo'])) ? $_GET['foo'] : 1;
More information on the ternary operator can be found in a previous blog of mine: The Ternary Operator.

The ternary operator is very powerful. As you can see, it has transformed 5 lines of code into one, but programmers hate repetition. $_GET['foo'] was written twice! The situation above is encountered so often that PHP 6 will accommodate for the repetition. At first, there was going to be a new language construct called ifsetor(), however the PHP developers settled on a new operator. The previous situations will look like the following in PHP 6:
$bar = $_GET['foo'] ?: 1;
The following will also be possible:
$bar = ($_GET['foo']==2) ?: 1;
In other words, if $_GET['foo'] does not equal 2, it will default to 1.

  • 0

That looks much better than the Ternary Operator. I saw a PHP 6 book yesterday at Barnes and Noble and thought of you. Have you had the chance to read any books on 6 yet?
    • 0
I don't think the authors of those books can know anymore about PHP 6 than you or I do - as the only facts regarding php 6 come from the meeting notes and everything else is speculation.
    • 0
Not all PHP6 books show all the features of the updated language. Most of them seem to go over the functions/operators etc. that have final notes. Other than that, they show warnings on the features that might change.

PHP6 so far is looking really good :) I can't wait for this new feature to come into play.
    • 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download