Jump to content

alternative to switch;case?


newb

Recommended Posts

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

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.';
}

 

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.