php - Can we use { to declare e variable variable?
I have a piece of code which I a trying to shorten using variable variable, wanted to check if this is a valid code.
Original code:
$town = ( $_POST['town'] ) ;
$county = ($_POST['county'] ) ;
// Update town user meta
if ( !empty( $town ) )
update_user_meta( $user_id, 'town', $town);
// Delete town user meta
else
delete_user_meta( $user_id, 'town' );
//Update county user meta
if ( !empty( $county ) )
update_user_meta( $user_id, 'county', $county);
// Delete county user meta
else
delete_user_meta( $user_id, 'county' );
Shortened code :
$fields = array("town","county");
foreach ($fields as $field) {
${$field} = $_POST[$field];
if ( !empty( $field ) ) { update_user_meta( $user_id, "$field", ${$field}); } else { delete_user_meta( $user_id, "$field" ); }
}
Without the shortened code, we can accommodate more variables, which is the goal.
Thanks for your time.
EDIT
Special thanks to all the negative voters. My last post here got 7 negative votes, here its 2 only so far. Com'n guys, break my last record.
On a more serious note, there must be a stricter policy by Stackoverflow about negative voting and there must be a scrutiny on such votes by other people - I feel, random mass negative votes like these can be highly demoralizing.
Answer
Solution:
You are probably looking for something like
Or something along those lines.
EDIT: But if you really need to define a list of fields you could do
Answer
Solution:
You already have an array you can use:
However, you need to run validation on the POST data and make sure you guard against sql injection