Mr Nick Posted July 12, 2010 Share Posted July 12, 2010 This isn't really a problem, I'm just looking for the best way to do this. I have a simple array that allows the different types of orders. What would be the best way to check and execute them? I've written a few and am wondering which would be the best to use. $orders = array("login", "gm", "email"); //Method 1 if(isset($_GET['order']) && in_array($_GET['order'], $orders)){ $order = $_GET['order']; } else { $order = 'login'; } //Method 2 $order = isset($_GET['sort']) ? in_array($_GET['sort'], $orders) ? $_GET['sort'] : "login" : "login"; //Method 3 $order = isset($_GET['sort']) ? $_GET['sort'] : "login"; $order = in_array($order, $orders) ? $order : "login"; I'll be using the same method to check for ASC and DESC. (This is sort of a MySQL question, but more on the php side so I'm putting it here). Quote Link to comment Share on other sites More sharing options...
Mr Nick Posted July 12, 2010 Author Share Posted July 12, 2010 I apologize with the second method. I meant to use && instead of another ?. $order = isset($_GET['sort']) && in_array($_GET['sort'], $orders) ? $_GET['sort'] : "login"; Quote Link to comment Share on other sites More sharing options...
JasonLewis Posted July 12, 2010 Share Posted July 12, 2010 Method 1, due to readability. It depends, they all do exactly the same thing. Are you after the fastest? They're probably all nearly the same. The only reason I say Method 1 is because it's far easier to read then the others. Quote Link to comment Share on other sites More sharing options...
Mr Nick Posted July 12, 2010 Author Share Posted July 12, 2010 Using ? and : is basically the same as using the if command. Although it depends what you're trying to do. I'll post a code using if first. $a = 0; $b = 0; $c = ""; if($a == $b){ $c = "A equals B"; } else { $c = "A does not equal B"; } $a = 0; $b = 0; $c = ""; $c = $a == $b ? "A equals B" : "A does not equal B"; Anyways, I've already solved this Quote Link to comment Share on other sites More sharing options...
JasonLewis Posted July 12, 2010 Share Posted July 12, 2010 Using ? and : is basically the same as using the if command. Although it depends what you're trying to do. I'll post a code using if first. $a = 0; $b = 0; $c = ""; if($a == $b){ $c = "A equals B"; } else { $c = "A does not equal B"; } $a = 0; $b = 0; $c = ""; $c = $a == $b ? "A equals B" : "A does not equal B"; Anyways, I've already solved this I'm well aware of the ternary operator, however as I said I find using an if statement improves readability. Depends what your going for. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.