Jump to content

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


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'] : "";
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.