0
votes

How can one make a for loop to compare variables like this (any language really but specifically for php):

Say I have var1 var2 var3 and I want an action to happen if two of the values are the same.

This is what I have but obviously it doesn't work as var1 will always equal var1, var2 will always equal var2 etc.

<?php for ($i = 1; $i <= 10; ++$i) { 
if (${'var'.$i} == ${'var'.$i}) {
// if match do something
}
else {
do something
}

Attempt for array_unique.

<?php
for ($i = 1; $i <= $number_of_seats; ++$i) {
$choices = array_unique(array("${'selected_seat'.$i}"));
if (count(${'selected_seat'.$i}) !== count($choices)) {
    echo 'action="fail.php"';
} 
else {
        echo 'action="success.php"';
        }
}

        ?> method="post">
1
you'd need two loops for the logic in the question - but why would you be doing this?AD7six
Can you clarify what you expect? Maybe give examples of lists that satisfy your condition and lists that don'tMatt Dodge
I have a ticket booking system and want to check if certain seats are chosen for each selection, and if the seats are the same then they aren't allowed to proceed. So if $var1 is 'A1' and $var2 is 'A1' it would send them to one page but if $var1 is 'A1 and $var2 is 'A2' it would send them to another page.user2209242
why don't you treat the user input as an array and just use array_unique? i.e. $choices = array_unique($input); if (count($input) !== count($choices)) { .... A more complete question may yield a more complete answer.AD7six
I attempted what you are saying although I don't really understand as I'm inexperienced. The only inputs I know of is when they are found in $_POST from boxes.user2209242

1 Answers

0
votes

Writing two loops would work but it would yield an O(n^2) algorithm.

You can sort the array of variables first and then traverse it seeing if any two of the consecutive values are equal. This yields a O(nlogn) algorithm.

Or you could use a HastTable to get a O(n) algorithm at the expenses of more programming time.

[edit]

As the efficiency is not a concern, the easiest way is to do a double for-loop:

<?php
for ($i = 1; $i <= 10; ++$i)
{ 
    for ($j = i+1; $j <= 10; ++$j)
    { 
        if (${'var'.$i} == ${'var'.$j})
        {
            // if match do something
        }
    }
}
?>

Note that you cannot should not have an else at that point.

In this code what }I'm doing is compare every element in [var1,var2, ...] to the elements to its right. Namely, I'm comparing var1 to var2, and then to var3, and so on...

Also notice you could change the first for termination to "i <= 9"

Hope it helps