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
https://forums.phpfreaks.com/topic/223416-php-variable-variables/
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";
}
}

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.