Alternative for checking the existence of a value in PHP I'm trying to create a wordpress plugin but checking for the existence of a value doesn't really feel right because there's a bunch of values that I have to check:

$flickr_key = '';
if(!empty($ecom['ecom_options_flickr_api'])){
  $flickr_key = $ecom['ecom_options_flickr_api'];
}

$flickr_secret = '';
if(!empty($ecom['ecom_options_flickr_secret'])){
  $flickr_secret = $ecom['ecom_options_flickr_secret'];
}


$freebase_key = '';
if(!empty($ecom['ecom_options_freebase_api'])){
  $freebase_key = $ecom['ecom_options_freebase_api'];
}

$ebay_key = '';
if(!empty($ecom['ecom_options_ebay_api'])){
  $ebay_key = $ecom['ecom_options_ebay_api'];
}


Is there a more elegant alternative for this?
As Hugo Dozois suggested, using isset with the ternary operator is a good way to do this.

If you can assume that the options have not been set to NULL or false and you can change the $ecom variable you can use array_merge or the union operator.

// Merge with your default values here.
$ecom += array('ecom_options_flickr_api'    =&gt; '',
               'ecom_options_flickr_secret' =&gt; '',
               'ecom_options_freebase_api'  =&gt; '',
               'ecom_options_ebay_api'      =&gt; '');

// Set the variables.
$flickr_key    = $ecom['ecom_options_flickr_api'];              
$flickr_secret = $ecom['ecom_options_flickr_secret'];
$freebase_key  = $ecom['ecom_options_freebase_api'];
$ebay_key      = $ecom['ecom_options_ebay_api'];


If they could be NULL or false you could set them using a short ternary as Hugo Dozois mentioned.  The indexes will now be set thanks to the union so you won't get Notices for undefined indexes.

Other Suggestions


I think your structure would be better represented as a multidimensional array:

$ecom['options'] = array('flickr_api'    => '',
                         'flickr_secret' => 'etc.');
Often intermediary variables such as $flickr_secret etc. are a bad idea IMO.  I prefer to use $ecom['options']['flickr_secret'] in my code.  I find aliases normally just confuse the code.