PHP: comparison of checking three elements

I have 3 product panels on the main page, and I am writing a CMS page for it. I am trying to check the items.

They are chosen by the three elements <select>, featured1, featured2and featured3. Defaults to<option value="0" selected>Select an element</option>

I need to check $_POSTto make sure that the user has not selected the same product for several panels.

I figured out what everyone $_POSTshould be $_POST['featuredN'] > 0, but I cannot find a logical way to handle 7 potential results. Using a logical table, where 1 is the setpoint.

1  2  3
-------
0  0  0
1  1  1
1  0  0
0  1  0
0  0  1
1  1  0
0  1  1

If the item is 0, I will not update it, but I want the user to be able to update one item if necessary.

, 0, , 0.

, . , , 1 0 0 0 .

, - , ! , !:)

+3
3

ifs?

if($_POST['featured1'] != 0 && $_POST['featured1'] != $_POST['featured2'] && $_POST['featured1'] != $_POST['featured3']) {
    // do something with featured1
}
if($_POST['featured2'] != 0 && $_POST['featured2'] != $_POST['featured1'] && $_POST['featured2'] != $_POST['featured3']) {
    // do something with featured2
}
if($_POST['featured3'] != 0 && $_POST['featured3'] != $_POST['featured1'] && $_POST['featured3'] != $_POST['featured2']) {
    // do something with featured3
}
+1

- :

function getFeaturedProducts() {
  $featuredProducts = array();
  foreach (array('featured1', 'featured2', 'featured3') as $key) {
    $value = intval($_POST[$key]);
    if (in_array($value, $featuredProducts)) {
      // throw validation error!
      return false;
    }
    if ($value) $featuredProducts[$key] = $value;
  }
  return $featuredProducts;
}

$products = getFeaturedProducts();
if ($products === false) {
  echo "You can't select the same product twice!";
} else {
  // $products will have the same keys as $_POST, but will only contain ones 
  // we want to update, i.e. if feature1 was 0, it will not be present at this point
  foreach ($products as $key => $value) {
    // sample update
    mysql_query("UPDATE featured SET product_id=$value WHERE key=$key");
  }
}
0

If you want to have unique elements in your array (for each element with a value above 0), you can do the following.

$selects = array(rand(0,2),rand(0,2),rand(0,2));

echo implode(",",$selects) . "\n";

function removeUnSelected($var) { return $var != 0; }
$selects = array_filter($selects,"removeUnSelected");

echo implode(",",$selects) . "\n";

if($selects == array_unique($selects))
{
    echo "true";
}
0
source

Source: https://habr.com/ru/post/1749173/


All Articles