Page 2 of 2

Re: General PHP question.

Posted: Wed Jan 06, 2010 10:43 pm
by Payton
Since you offered I do have some questions. Sorry for bumping the topic.

Why do you write the variables like this?

Code: Select all

$username = (isset($_POST['username'])) ? $_POST['username'] : "";
    $password = (isset($_POST['password'])) ? $_POST['password'] : "";

Re: General PHP question.

Posted: Wed Jan 06, 2010 11:13 pm
by Griven
That's a shorthand way of setting a default value.

This...

Code: Select all

$username = (isset($_POST['username'])) ? $_POST['username'] : "";
Is the same as this...

Code: Select all

if (isset($_POST['username'])){
  $username = $_POST['username'];
} else {
  $username = "";
}

Re: General PHP question.

Posted: Wed Jan 06, 2010 11:29 pm
by flying_circus
Yup, as Griven said, it's a shortcut. I only like to do it that way, if it doesnt cloud up the read-a-bility of the code. It's called a ternary operator and is the 2nd example on this page:

http://www.php.net/manual/en/language.expressions.php

(#1) ? #2 : #3;

If the expression in #1 (which is an if statement) returns true, then do #2, else do #3.

I always use that method when fetching $_GET or $_POST variables. It ensures the variable that I am trying to access is set, so I only have to check if it's empty later.

Re: General PHP question.

Posted: Thu Jan 07, 2010 12:45 am
by lara6smith
I became fan of your posts. I like to read them again and again. Your posts are so informative and helpful. You give information in best possible way.
Jenny Craig
Blockbuster
Jenny Craig