比较字符串,只获取某些不匹配的字符串

时间:2017-02-10 05:03:11

标签: php arrays string performance variables

我有一些字符串,我希望变量彼此不相等。

例如:

$username
$email
$firstname
$lastname
$gender

$_POST['username'];
$_POST['email'];
$_POST['firstname'];
$_POST['lastname'];
$_POST['gender'];

我想将$username$_POST['username']$email$_POST['email']等进行比较......

这就是我想要比较的方式:

$username !== $_POST['username']等等......

我怎样才能得到彼此不相等的变量(不是$_POST变量)?

3 个答案:

答案 0 :(得分:1)

有这么多的值,如果你知道你的字段,我会使用数组。

$vars = ['username' => 'value', 'email' => 'value',
        'firstname' => 'value', 'lastname' =>'value', 'gender'  => 'value'];
foreach($vars as $key => $value){
  if($_POST[$key] !== $value){
    //does not match
  }else{
    // does match
  }
}

答案 1 :(得分:1)

由于POST参数是以数组形式出现的,最简单的方法是将变量放在数组中并使用array_diff计算差异:

$variables = [
    'username' => $username,
    'email' => $email,
    'firstname' => $firstname,
    'lastname' => $lastname,
    'gender' => $gender
];

$non_matching = array_diff($variables, $_POST);

echo "Non matching variables: " . join(', ', array_keys($non_matching));

将打印出如下内容:

Non matching variables: username, firstname

答案 2 :(得分:1)

您可以对每个数组键使用foreach,并使用$$key

$username = 'username';
$email    = 'email~';
$gender   = 'not gender';

$_POST['username']  = 'username';
$_POST['email']     = 'email';
$_POST['firstname'] = 'firstname';
$_POST['lastname']  = 'lastname';
$_POST['gender']    = 'gender';

foreach ($_POST as $key => $value) {
    if ( !isset($$key) ) {
        echo 'The variable $' . $key . ' is undefined.' . PHP_EOL;
        continue;
    }
    echo 'Compare $_POST[\'' . $key . '\'] and $' . $key . ': ' . ( $value === $$key ? 'true' : 'false' ) . PHP_EOL;
}

结果:

Compare $_POST['username'] and $username: true
Compare $_POST['email'] and $email: false
The variable $firstname is undefined.
The variable $lastname is undefined.
Compare $_POST['gender'] and $gender: false