[nycphp-talk] Accessing non-existent array elements ok?
tedd
tedd at sperling.com
Mon Aug 18 08:44:14 EDT 2008
At 3:10 PM -0700 8/17/08, Kristina Anderson wrote:
>I've seen similar syntax before, in some code Tedd & I were working
>with a couple of months back...and just want to make sure I fully
>understand what is actually happening with it.
-- Kristina:
The Ternary Operator is the "?" -- it is simply shorthand way of
writing "this else that".
"? this : that"
If used in an assignment
var = if true ? this : that
I use it primarily for this:
$action = isset($_GET['action']) ? $_GET['action'] : null;
$action = isset($_POST['action']) ? $_POST['action'] : null;
$action = isset($_SESSION['action']) ? $_SESSION['action'] : null;
You see, if you try to check for the existence of an index that is
not there, then you'll generate an error. But by using the above, it
assures: a) no error will be generated; b) and your var will be set
to whatever you want the default to be.
I don't like using the Ternary Operator elsewhere because you can
generate some very strange looking code, such as:
$var ?
$a = a()
:
$a = b();
Note, the above works and is the same as:
if($var)
{
$a = a();
}
else
{
$a = b();
}
But, which is easier to understand three months from now?
Cheers,
tedd
--
-------
http://sperling.com http://ancientstones.com http://earthstones.com
More information about the talk
mailing list