Jump to content

PHP variable variables?


jacksinful

Recommended Posts

I am not sure how to do the below, would variable variables be the way -- those are a new and confusing thing for me :-/

 

i have an array:

 

$contactData = array('admin_firstName' => 'John', 'admin_lastName' => 'Smith', 'user_firstName' => 'Betty', user_lastName => 'Jones'); 

 

I have a function that little function that looks like this:

function compare($contactSet, $var, $value){

global $contactData;

    $key = $contactData . "['" . $contactSet . "_" . $var ."']";
    //above doesnt work, but you can see how the array key is constructed
    
if ($key == $value) { 
// So, if the array key varied it would look like:
// if ($contactData['admin_firstName'] == $value

	echo "same";

} else {

	echo "different";

}

}

 

and then I want to call it like this:

compare('admin', 'firstName', 'John'); //would echo "same";

 

Any help is greatly appreciated. I have often wanted to use variable variables, or whatever this would be called, but don't know to pull it off. I can add another example if this wasnt clear enough.

Link to comment
Share on other sites

PHP variable variables are not what you are looking for here. You only need to glue two strings together to get the key.


function compare($contactSet, $var, $value){



global $contactData;

    $key = $contactSet . '_' . $var;
    //above doesnt work, but you can see how the array key is constructed
if ($contactData[$key] == $value) { 
// So, if the array key varied it would look like:
// if ($contactData['admin_firstName'] == $value
echo "same";
} else {
echo "different";
}
}

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.