selecting unique values from a column
To select unique values from a column in PHP, you can use the array_unique
function. This function removes duplicate values from an array and returns an array with only unique values.
For example, let's say you have an array of values called $values
:
<?php
$values = array("a", "b", "c", "a", "b", "d");
Watch a video course
Learn object oriented PHP
You can use array_unique
to remove the duplicate values and get an array with only unique values:
<?php
$values = array("a", "b", "c", "a", "b", "d");
$unique_values = array_unique($values);
print_r($unique_values);
This will output:
Array ( [0] => a [1] => b [2] => c [5] => d )
Note that the keys of the array will be reset, so the values will be re-indexed starting from 0. If you want to preserve the keys of the original array, you can pass the SORT_REGULAR
flag as the second argument to array_unique
:
<?php
$values = array("a", "b", "c", "a", "b", "d");
$unique_values = array_unique($values, SORT_REGULAR);
print_r($unique_values);
This will output:
Array ( [0] => a [1] => b [2] => c [5] => d )