Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 比较字符串并仅获取不带';不匹配_Php_Arrays_String_Performance_Variables - Fatal编程技术网

Php 比较字符串并仅获取不带';不匹配

Php 比较字符串并仅获取不带';不匹配,php,arrays,string,performance,variables,Php,Arrays,String,Performance,Variables,我有几个字符串,我想要的变量彼此不相等 例如: $username $email $firstname $lastname $gender $_POST['username']; $_POST['email']; $_POST['firstname']; $_POST['lastname']; $_POST['gender']; 我想比较$username和$\u POST['username'],$email和$\u POST['email'],等等 这就是我想要比较它的方式: $user

我有几个字符串,我想要的变量彼此不相等

例如:

$username
$email
$firstname
$lastname
$gender

$_POST['username'];
$_POST['email'];
$_POST['firstname'];
$_POST['lastname'];
$_POST['gender'];
我想比较
$username
$\u POST['username']
$email
$\u POST['email']
,等等

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

$username!==$_发布['username']


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

有这么多值,如果您知道出现的字段,我会使用数组

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

由于POST参数是以数组形式输入的,因此最简单的方法是将变量也放入数组中,并使用以下公式计算差异:

它将打印出如下内容:

Non matching variables: username, firstname

您可以对每个数组键使用
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

如果($username!=$\u POST['username'])使用此…请检查语法@SoniyaReddy@SougataBose我只是比较用户名不能等于$\u POST['username']请告诉我我做错了什么?@jasonmokio?@SoniyaReddy,应该是
=
==
,而不是
=
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