newb Posted June 25, 2012 Share Posted June 25, 2012 whats a more efficient way of achieviing the same results with less code: switch ($info) { case name: return $row['username']; break; case group: return $row['usergroupid']; break; case email: return $row['email']; break; case posts: return $row['posts']; break; case usertitle: return $row['title']; break; case securitytoken: return $row['securitytoken']; break; case lastvisitdate: return $row['lastvisitdate']; break; case joindate: return $row['joindate']; break; case pmtotal: return $row['pmtotal']; break; case pmunread: return $row['pmunread']; break; nothing is wrong with this btw just looking for a better way of getting columns from the database w/o having to go back and add a case each time i want to. Link to comment https://forums.phpfreaks.com/topic/264773-alternative-to-switchcase/ Share on other sites More sharing options...
PFMaBiSmAd Posted June 26, 2012 Share Posted June 26, 2012 You should use a switch/case statement when you have different logic you need to run. For simple key/value lookups, you should use some form of mapping to associate the key with the value. Some different methods - <?php // if the $info value exactly matchs the $row associative index names (which is not what you show for some of your key/value pairs), with no error checking (if the $info value doesn't exist, you get null data back) return $row[$info]; ?> <?php // same as above, but with some error checking if(isset($row[$info])){ return $row[$info]; } else { return 'Invalid info index name.'; } ?> <?php // using a lookup array to associate the $info values with the actual index names // just modify the $lookup array to add/remove/change any entries $lookup = array('name'=>'username','group'=>'usergroupid', 'the rest of your key/value pairs go here...'); if(isset($lookup[$info])){ // lookup key found if(isset($row[$lookup[$info]])){ return $row[$lookup[$info]]; } else { return 'No data index with the requested name.'; } } else { return 'Invalid info index name.'; } Link to comment https://forums.phpfreaks.com/topic/264773-alternative-to-switchcase/#findComment-1356967 Share on other sites More sharing options...
.josh Posted June 26, 2012 Share Posted June 26, 2012 nothing wrong with your code? well then, I guess you must have a lot of constants defined... Link to comment https://forums.phpfreaks.com/topic/264773-alternative-to-switchcase/#findComment-1356968 Share on other sites More sharing options...
newb Posted June 26, 2012 Author Share Posted June 26, 2012 thanks, worked. Link to comment https://forums.phpfreaks.com/topic/264773-alternative-to-switchcase/#findComment-1356984 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.