General PHP question.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Payton
Forum Commoner
Posts: 33
Joined: Sun Dec 06, 2009 4:03 pm

Re: General PHP question.

Post 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'] : "";
Griven
Forum Contributor
Posts: 165
Joined: Sat May 09, 2009 8:23 pm

Re: General PHP question.

Post 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 = "";
}
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: General PHP question.

Post 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.
lara6smith
Forum Newbie
Posts: 1
Joined: Thu Jan 07, 2010 12:28 am

Re: General PHP question.

Post 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
Post Reply