Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_unique function

Removes duplicate values from the array and returns a new array without duplicates.

Description / Descripción
array_unique(array $array, int $flags = SORT_STRING): array
Sintaxis / Sintax
$new_array = array_unique($my_array);


$array – The array from which duplicate values will be removed.

$flags – This parameter is optional, and its default value is SORT_STRING. With it, you can change the way values are compared.

Comparison type flags:

  • SORT_REGULAR – No changes in types, no casting.
  • SORT_NUMERIC – Compares items numerically.
  • SORT_STRING – Compares items as strings.
  • SORT_LOCALE_STRING – Compares items as strings based on the current locale settings.
To better understand, consider that a comparison will be like variableA === variableB. When we change the comparison type flag, we are essentially doing something like (type)variableA === (type)variableB.


It returns the array without duplicated values.


In this example, we will see a case where we might not want to make the values unique. In other cases, array_unique would work quite well. In this scenario, as in the one that follows, we need to think carefully before applying this function. Will this affect me?

Ejemplo simple
$caracteristicas_auto = [
    "marca" => "Toyota",
    "modelo" => "Camry",
    "año" => 2022,
    "color" => "Azul",
    "color_llantas" => "Azul",
    "motor" => "2.5L",
    "tracción" => "Delantera"
array(6) {
  string(6) "Toyota"
  string(5) "Camry"
  string(4) "Azul"
  string(4) "2.5L"
  string(9) "Delantera"
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category