How to use php array_unique function?

青灯夜游
Release: 2023-02-22 18:32:01
Original
6873 people have browsed it

array_unique() is a built-in function in PHP. The syntax is array_unique(array, sort_flags), which is used to remove duplicate values from an array. If there are multiple elements in the array with the same value, the first occurring element will be retained and other elements with the same value will be removed from the array.

How to use php array_unique function?

#php array_unique() function how to use?

php The array_unique() function is used to remove duplicate values from an array.

Basic syntax:

array_unique(array , sort_flags)
Copy after login

Parameters:

1, array: required. Specifies an array.

2. Sortingtype: Optional, specifies how to compare array elements/items. Can be used to modify sorting behavior using the following values:

● SORT_STRING - Default value. Compare items as strings.

● SORT_REGULAR - Compares items normally (does not change type)

● SORT_NUMERIC - Compares items numerically.

● SORT_LOCALE_STRING - Compares items as strings based on the current locale (locale) settings.

Return value:The array_unique() function returns the filtered array after removing all duplicates from the array.

Instructions:First sort the values as strings, then only retain the first encountered key name for each value, and then ignore all subsequent key names. This does not mean that the first occurrence of the same value in an unsorted array will be preserved.

Explanation:Two elements are considered equal if and only if (string) $elem1 === (string) $elem2, that is, when the string represents equal At the same time, the first element will be used.

Note:array_unique() does not work with multi-dimensional arrays.

Let’s take a look at how to use the php array_unique() function through an example.

Example 1:

"php中文网","b"=>"西门","c"=>"php中文网"); print_r(array_unique($a)); ?>
Copy after login

Output:

Array ( [a] => php中文网 [b] => 西门 )
Copy after login

Example 2:

"php中文网","2"=>"灭绝师太","c"=>"php中文网",'4' => "欧阳克"); print_r(array_unique($b)); ?>
Copy after login

Output:

Array ( [1] => php中文网 [2] => 灭绝师太 [4] => 欧阳克 )
Copy after login

The above is the detailed content of How to use php array_unique function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!