Jump to content

better if statement?


student101

Recommended Posts

Is there a better way to write this if statement?Option1:

if (isset($_GET['item']) || isset($_POST['item'])){   $path = 'uploads/file/'.$filename;}else{    $path = 'uploads/'.$filename;}

Option2:

if ('item' != $_GET['news'] || 'item' !=  $_GET['events'] || 'item' != $_GET['download']){    $path = 'uploads/file/'.$filename;}else{    $path = 'uploads/'.$filename;}

Link to comment
Share on other sites

What exactly is it that you're trying to do? There isn't a more appropriate way - boh things work, both are appropriate, but they both work differently, so they are appropriate in different contexts.

Link to comment
Share on other sites

Since you're setting the same variable in both the if and else blocks you can write the first one like this, just to make it shorter:$path = isset($_GET['item']) || isset($_POST['item']) ? 'uploads/file/'.$filename : 'uploads/'.$filename;

Link to comment
Share on other sites

Not sure what you mean, they both check if item contains anything?
No they don't.
isset($_GET['item']) || isset($_POST['item'])

checks if there is an "item" variable in the query string or in the request body.This will be true for a URL like (for example):index.php?itemorindex.php?item=somethingand false forindex.php?news=itemorindex.php?events=notItem

'item' != $_GET['news'] || 'item' !=  $_GET['events'] || 'item' != $_GET['download']

checks if there is a variable "news" or "events" or "download" in the query string that has a value different than the value "item".This will be true for a URL like:index.php?events=notItemorindex.php?news=notItemand false forindex.php?news=item&events=item&download=item

Link to comment
Share on other sites

You can do that with

isset($_GET['item']) && !empty($_GET['item'])

This checks if a variable called "item" exists and is not empty. It will be true toindex.php?item=1orindex.php?item=somethingand will be false onindex.php?itemorindex.php?notItemYou could write this condition in either an if statement or in the short form (a.k.a. "ternary operator").

Link to comment
Share on other sites

Now I need to learn, "ternary operator" ?
That's what justsomeguy showed you above.
$path = isset($_GET['item']) || isset($_POST['item']) ? 'uploads/file/'.$filename : 'uploads/'.$filename;

The form

condition ? if_true : if_false

is called "ternary operator". See its description in the PHP manual.

Link to comment
Share on other sites

Yes, if you're using empty it's not necessary to use isset.
Maybe it's a habbit from an old version or something... I recall I once used empty on a non existent variable, and got a notice for an undefined variable. It could've been removed in recent versions though... it's been a long time since I last tried the same thing.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...