0

There's been discussions about this topic before, but I haven't been able to get any of the examples from them to work in my case. Hoping this is an easy fix that may help others having similar problems.

I have an html form that takes a series of 5 numbers as an array. I simply want to print the numbers without any duplicates. I'm trying to accomplish this using array_unique().

The Form:

<p>Enter a series of numbers.  Any duplicates will be removed, then 
displayed on the screen.</p>
<form action="rDuplicate.php" method="post">
Number 1: <input type="number" name="number[]"><br>
Number 2: <input type="number" name="number[]"><br>
Number 3: <input type="number" name="number[]"><br>
Number 4: <input type="number" name="number[]"><br>
Number 5: <input type="number" name="number[]"><br>
<input type="submit">
</form>

The PHP:

<?php 
    $values = array($_POST);
    $result = array_unique($values);
    print_r($result);
?>

Current Sample Output:

Array ( [number] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 2 [4] => 1 ) )
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
Justiciar
  • 356
  • 1
  • 3
  • 20

1 Answers1

1
<?php
$numbers = $_POST['number']  ?? [];
$numbers = is_array($numbers)
                ? array_filter($numbers, 'ctype_digit')
                : [];
$numbers = array_unique($numbers);

var_dump($numbers);

Long form:

if(isset($_POST['number']))
{
    $numbers = $_POST['number'];
} else {
    $numbers = [];
}
if(is_array($numbers)) {
    $numbers = array_filter($numbers, 'ctype_digit');
} else {
    $numbers = [];
}
$numbers = array_unique($numbers);   

In the long hand version, we can use the ternary operator to contract the if else:

$numbers = isset($_POST['number']) ? $_POST['number'] : [];

We can contract that further with the null coalescing operator:

$numbers = $_POST['number'] ?? [];

If you want to ensure you only have an array of integers (or more precisely integers in strings) passed from your form, you can filter your array.

$numbers = array_filter($numbers, 'ctype_digit');

Note: You cannot trust user input.

Progrock
  • 7,373
  • 1
  • 19
  • 25
  • 1
    Thanks! This does work. Could you possibly explain what is happening during the code that comes after the ?'s. `?? null;` and `? array_unique($numbers) : [];` for example. I'm just starting out using php and not sure what these sections are doing. – Justiciar Apr 25 '18 at 21:36
  • @Justiciar, I've slightly changed the code to include an input filter, to ensure we end up with an array of integers or an empty array. And added the long form of the code. – Progrock Apr 26 '18 at 08:09