Reputation: 877
I have 6 Select input fields and all the 6 input fields have same options value, but i want that each of select input value should be unique for e.g
Input 5 and Input 6 are optional input field but if they are filled then they should be validated for unique value
Input1 Input2 Input3 Input4 Input5 Input6
value1 value1 value1 value1 value1 value1
value2 value2 value2 value2 value2 value2
value3 value3 value3 value3 value3 value3
Now if user selected value1
in Input1
then he can't choose value1
in other select fields
I know i can do it using if elseif else
but it will not be that professional, is there a better way of validating it.
Upvotes: 0
Views: 79
Reputation: 954
This is something I came up with, but it is not the best way of doing this.
<?php
if ($_POST) {
$data = [];
$data[] = $_POST['Input1'];
$data[] = $_POST['Input2'];
$data[] = $_POST['Input3'];
$data[] = $_POST['Input4'];
//optional values
if ("" == trim($_POST['Input5'])) {
$data[] = $_POST['Input5'];
}
if ("" == trim($_POST['Input6'])) {
$data[] = $_POST['Input6'];
}
//count post elements
$count = count($data);
// get unique elements from array
$result = array_unique($data);
if (count($result) !== $count) {
echo 'Duplicated data';
} else {
echo 'All are unique';
}
}
I think a better solution would be to look into some Javascript Validators
Don't Reinvent The Wheel, Unless You Plan on Learning More About Wheels
Upvotes: 1
Reputation: 2943
Take all input of fields in one variable, and then get only unique values.
Please see below. This will help.
if ($_POST) {
$validate_data = [];
$is_valid = FALSE;
$validate_data[] = $_POST['Input1'];
$validate_data[] = $_POST['Input2'];
$validate_data[] = $_POST['Input3'];
$validate_data[] = $_POST['Input4'];
// get unique elements from array
$result = array_unique($validate_data);
// if array size is equal to no of input fields then means all are unique
// else it has duplicate values
if (count($result) != 4 ) {
$is_valid = FALSE;
} else {
// Validate optional fields
if (isset($_POST['Input5']) && in_array($_POST['Input5'], $result)) {
$is_valid = FALSE;
} else if (isset($_POST['Input6']) && in_array($_POST['Input6'], $result)) {
$is_valid = FALSE;
} else {
$is_valid = TRUE;
}
}
echo ($is_valid) ? 'All are unique.' : 'Invalid Data';
}
Upvotes: 1