0

is there a way to write an if else statement by the input field name?

I have a loop that dynamically creates 9 input field,

The loop

for($i=0; $i<($n*$n); $i++){
    echo "<tr>";

for($j=0; $j<($n*$n); $j++){
        $number = "column".$i.$j;

        if($i%$n==0 && $j%$n==0 && $j!==0 && $i!==0){
        echo "<td><input class='field'  type='text' name=$number value=$_POST[$number]></td>";

        }

and the output is this.

<input class="field" type="text" name="column00" value="1">
<input class="field" type="text" name="column01" value="2">
<input class="field" type="text" name="column02" value="1">
.....
<input class="field" type="text" name="column09" value="3">

So what I am trying to do is, that if there is a inputed number on row 1 to 9 that is equal to another number in row 1 to 9 it will echo out that there more than one number thats equal to each other.

I tried something like this but it wouldn't work.

if($number==$number){

echo = "equal number in the same row";

}
Dymond
  • 2,158
  • 7
  • 45
  • 80
  • I can't see how that code gives such output :) you're building a table in your code and it magically comes out as input fields? – Ja͢ck Dec 16 '13 at 22:39
  • Wait, is this a sudoku game by any chance? :) – Ja͢ck Dec 16 '13 at 22:40
  • @Jack you're correct sir :) – Dymond Dec 16 '13 at 22:42
  • Looks to me like this creates 100 input fields in a 10x10 grid, not just 9. Anyway, the way to do what you want is to make an array of all the numbers entered in the row. Then call `array_unique()` on that. If the result of this has 10 elements, then there were no duplicates. – Barmar Dec 16 '13 at 22:45
  • Also it looks like you want to be checking against the values coming through the $_POST instead of just $number. – nick Dec 16 '13 at 22:47

2 Answers2

1

Make an array of all the inputs from a row. Then do:

$unique = array_unique($row_values);
if (count($unique) != count($row_values)) {
    echo "No duplicate numbers in a row!";
}

Do the same thing for each column.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Use field names in this form:

<input name="number[<row>][<column>]" ...

So, for instance:

<input name="number[0][0]" value="1" />
<input name="number[0][1]" value="2" />
<input name="number[0][2]" value="5" />
<input name="number[0][3]" value="3" />
...
<input name="number[1][0]" value="4" />
<input name="number[1][1]" value="9" />

When posted, you will receive a two-dimensional array:

[[1, 2, 5, 3, ...], [4, 9, ...]]

Now it basically becomes an array problem you have to solve for:

  1. All rows and columns
  2. Rows and columns within each grid

To help you find the value that occurs multiple times in an array:

$multiples = array_filter(array_count_values($arr), function($freq) {
    return $freq > 1;
});

// outputs a non-empty array with the numbers that occur more than once.
print_r(array_keys($multiples)); 
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309