Adeus Posted January 7, 2009 Share Posted January 7, 2009 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. Link to comment https://forums.phpfreaks.com/topic/139846-solved-numerous-if-statements-cluttered-code/ Share on other sites More sharing options...
JonnoTheDev Posted January 7, 2009 Share Posted January 7, 2009 use a loop for($x = 1; $x <= 20; $x++) { if(isset($_GET['item_'.$x])) { $_SESSION['item_'.$x] = $_GET['item_'.$x]; } elseif(!isset($_SESSION['item_'.$x])) { $_SESSION['item_'.$x] = ""; } } Link to comment https://forums.phpfreaks.com/topic/139846-solved-numerous-if-statements-cluttered-code/#findComment-731592 Share on other sites More sharing options...
gevans Posted January 7, 2009 Share Posted January 7, 2009 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'] : ""; ?> Link to comment https://forums.phpfreaks.com/topic/139846-solved-numerous-if-statements-cluttered-code/#findComment-731595 Share on other sites More sharing options...
Adeus Posted January 7, 2009 Author Share Posted January 7, 2009 Thanks guys! Perhaps I could use both strategies and do something like this? <?php for($x = 1; $x <= 20; $x++) { $_SESSION['item_'.$x] = (isset($_GET['item_'.$x])) ? $_GET['item_'.$x] : ""; } ?> I'm going to give it a try. Link to comment https://forums.phpfreaks.com/topic/139846-solved-numerous-if-statements-cluttered-code/#findComment-731608 Share on other sites More sharing options...
gevans Posted January 7, 2009 Share Posted January 7, 2009 Nice thinking batman!!!! Link to comment https://forums.phpfreaks.com/topic/139846-solved-numerous-if-statements-cluttered-code/#findComment-731612 Share on other sites More sharing options...
Adeus Posted January 7, 2009 Author Share Posted January 7, 2009 Nice thinking batman!!!! Haha, thanks. The "ternary loop" works fine. Much appreciated! Link to comment https://forums.phpfreaks.com/topic/139846-solved-numerous-if-statements-cluttered-code/#findComment-731632 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.