Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_unique()

Example

Eliminate duplicate values from an array.

<?php
$a=array(“a”=>“red”,“b”=>“green”,“c”=>“red”);
print_r(array_unique($a));
?>

Definition and Usage

The array_unique() function removes duplicate values from an array, retaining only the first occurrence of each value and discarding subsequent duplicates.

 

Note: The resulting array will preserve the original key types of the first occurrence.

Syntax

array_unique(array, sorttype)

Parameter Values

 

Parameter

Description

array

Required. Providing an array.

sorttype

Optional. Specifies how to compare the array elements. Possible values are:

  • SORT_STRING – Default. Compare items as strings.
  • SORT_REGULAR – Compare items normally (without changing types).
  • SORT_NUMERIC – Compare items numerically.
  • SORT_LOCALE_STRING – Compare items as strings based on the current locale.

Technical Details

Return Value:

Returns the modified array.

PHP Version:

4.0.1+

PHP Changelog:

PHP 7.2: When sorttype is set to SORT_STRING, this returns a new array with the unique elements added.

PHP 5.2.9: The default value of sorttype was changed to SORT_REGULAR.

PHP 5.2.1: The default value of sorttype was reverted to SORT_STRING.