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

 

Link to comment
Share on other sites

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.