开发者

A better way to see if a variable isset php

Hi I just was wondering if there is a better way to do something like this:

$openid = $_SESSION['openiduserdata'];
if (isset($openid['namePerson/friendly']))
    {$username = $openid['namePerson/friendly'];}
if (isset($openid['namePerson/first']))
    {$firstname = $openid['namePerson/first'];}
if (isset($openid['namePerson/last']))
    {$lastname = $openid['namePerson/last'];}
if (isset($openid['birthDate']))
    {$birth = $openid['开发者_JAVA技巧birthDate'];}
if (isset($openid['contact/postalCode/home']))
    {$postcode = $openid['contact/postalCode/home'];}
if (isset($openid['contact/country/home']))
    {$country = $openid['contact/country/home'];}
if (isset($openid['contact/email']))
    {$email = $openid['contact/email'];}


$variables = array('openid' => 'openiduserdata', 'username' => 'namePerson/friendly', 'firstname' => 'namePerson/first', 'lastname' => 'namePerson/last', 'birth' => 'birthDate', 'postcode' => 'contact/postalCode/home', 'country' => 'contact/country/home', 'email' => 'contact/email');

foreach ($variables as $name => $key)
  if (isset($openid[$key]))
    $$name = $openid[$key];


If your goal is to avoid PHP notices, just prefix the array variable with @:

$username = @$openid['namePerson/friendly'];


If you are trying to set only those options that are not set in the array to a default value, one solution would be to create an array containing all of the default values, and then merge the incoming array with the default array.

<?php    
$defaults = array('name' => 'Anonymous','gender' => 'n/a');
$data = array_merge($defaults, $_POST);
// now data includes all the post parameters, however, those parameters that don't exist will be the default value in $data


Try to create function just like this:

function get_value_or_default($array, $key, $default = null)
{
    if (array_key_exists($key, $array))
    {
        return $array[$key];
    }
    else
    {
        return $default;
    }
}

$username = get_value_or_default($openid, 'namePerson/friendly');


$openid = array_merge(
   array('namePerson/friendly' => NULL,   // Or an empty string if you prefer.
         'namePerson/first'    => NULL,
         'namePerson/last'     => NULL),  // etc.
   $_SESSION['openiduserdata']);

// Now you know that the keys are set.
// Then if you really need them separate:
$username = openid['namePerson/friendly'];
$firstname = openid['namePerson/first'];
$lastname = openid['namePerson/last'];
// etc.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜