selecting unique values from a column
To select unique values from a column in PHP, you can use the array_unique function.
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:
How to select unique values from a column in PHP?
<?php
$values = array("a", "b", "c", "a", "b", "d");
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
You can use array_unique to remove the duplicate values and get an array with only unique values:
How to select unique values from a column in PHP using array_unique() function?
<?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:
How to select unique values from a column in PHP using array_unique() function with preserving the keys of the original array?
<?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
)