Author: Admin/Publisher |finished | checked
PHP array_unique function
Removes duplicate values from the array and returns a new array without duplicates.
Description / Descripciónarray_unique(array $array, int $flags = SORT_STRING): arraySintaxis / Sintax
$new_array = array_unique($my_array);
Parameters
$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.
Return
It returns the array without duplicated values.
Examples
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?
$caracteristicas_auto = [ "marca" => "Toyota", "modelo" => "Camry", "año" => 2022, "color" => "Azul", "color_llantas" => "Azul", "motor" => "2.5L", "tracción" => "Delantera" ]; var_dump(array_unique($caracteristicas_auto));
array(6) { ["marca"]=> string(6) "Toyota" ["modelo"]=> string(5) "Camry" ["año"]=> int(2022) ["color"]=> string(4) "Azul" ["motor"]=> string(4) "2.5L" ["tracción"]=> 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