I have a few strings and i want the variables that don't equal each other.
For example:
$username
$email
$firstname
$lastname
$gender
$_POST['username'];
$_POST['email'];
$_POST['firstname'];
$_POST['lastname'];
$_POST['gender'];
i want to compare $username
with $_POST['username']
, $email
with $_POST['email']
, etc...
this is how i want to compare it:
$username !== $_POST['username']
, etc...
how can i get the variables (not $_POST
variables) that DON'T equal each other?
with so many values, and if you know the fields that are coming at you, I would use arrays.
$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
}
}
Since the POST parameters are coming in as an array, the simplest approach would be to put your variables also in an array and calculate the difference using 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));
Which will print out something like:
Non matching variables: username, firstname
You can use foreach
to each array key and $$key
to do.
$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;
}
Result:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.