查看变量是否设置为php的更好方法

时间:2011-08-14 05:26:34

标签: php php-5.3

嗨,我只是想知道是否有更好的方法来做这样的事情:

$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['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'];}

5 个答案:

答案 0 :(得分:5)

$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];

答案 1 :(得分:2)

如果您的目标是避免PHP通知,只需在数组变量前加上@

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

答案 2 :(得分:1)

如果您尝试仅将未在数组中设置的选项设置为默认值,则一种解决方案是创建包含所有默认值的数组,然后将传入数组与默认数组合并。

<?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

答案 3 :(得分:0)

尝试创建这样的函数:

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');

答案 4 :(得分:0)

$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.