Jump to content

[SOLVED] Numerous "if" statements -- cluttered code


Adeus

Recommended Posts

Hi, I would still consider myself a PHP novice. I have a question concerning best methods/practices. Would there be an easier/less cluttered way of doing something like this?

 

if (isset($_GET['item_1'])) { $_SESSION['item_1'] = $_GET['item_1']; } elseif (!isset($_SESSION['item_1'])) { $_SESSION['item_1'] = ""; }
if (isset($_GET['item_2'])) { $_SESSION['item_2'] = $_GET['item_2']; } elseif (!isset($_SESSION['item_2'])) { $_SESSION['item_2'] = ""; }
if (isset($_GET['item_3'])) { $_SESSION['item_3'] = $_GET['item_3']; } elseif (!isset($_SESSION['item_3'])) { $_SESSION['item_3'] = ""; }
//...and so on...

 

I have about 20 or so of these "if" statements sitting atop my script. There has to be a better way. Thanks for any references or help.

This is a bit cleaner and should work for you :)

 

<?php
$_SESSION['item_1'] = (isset($_GET['item_1']))? $_GET['item_1'] : "";
$_SESSION['item_2'] = (isset($_GET['item_2']))? $_GET['item_2'] : "";
$_SESSION['item_3'] = (isset($_GET['item_3']))? $_GET['item_3'] : "";
?>

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.