php - Can we use { to declare e variable variable?

84

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.

749

Answer

Solution:

You are probably looking for something like

foreach($_POST as $key => $value){
   if ( !empty( $value) ) { update_user_meta( $user_id, $key, $value); } 
   else { delete_user_meta( $user_id, $key); } 
}

Or something along those lines.

EDIT: But if you really need to define a list of fields you could do

$fields = array("town","county");

foreach($fields as $field){
       if ( !empty($_POST[$field]) ) { update_user_meta( $user_id, $field, $_POST[$field]); } 
       else { delete_user_meta( $user_id, $field ); } 
}
935

Answer

Solution:

You already have an array you can use:

foreach( $_POST as $field => $value ){
  if ( !empty( $value ) ) update_user_meta( $user_id, $field, $value);
}

However, you need to run validation on the POST data and make sure you guard against sql injection

People are also looking for solutions to the problem: javascript - IE HTML5 audio files hang on windows localhost - works in all other browsers and on web

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.