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 ) )
<?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.