Can the values of an array in php be repeated?

青灯夜游
Release: 2023-03-16 20:34:02
Original
2029 people have browsed it

The values of the array can be repeated. In PHP, the key of an array is unique and cannot exist repeatedly, but the key value of an array can exist repeatedly. Methods to deal with duplicate values: 1. Use the array_unique() function to delete duplicate values in the array; 2. Use the array_count_values() function to count the number of occurrences of all values in the array and return an associative array with the keys of its elements. The name is the value of the original array, and the key value is the number of times the value appears in the original array.

Can the values ​​of an array in php be repeated?

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

In php, the key of the array The name (key) is unique and cannot exist repeatedly, but the key value (value) of the array can exist repeatedly.

$arr=array("A","Cat","Dog","A","Dog","a",3,4);
Copy after login

Can the values ​​of an array in php be repeated?

As you can see, in the above example, the element values "A" and "Dog" have duplicate values.

Handling functions for duplicate values in PHP arrays

For duplicate values, PHP provides a variety of built-in processing functions, two of which are introduced below:

  • array_unique()

  • array_count_values()

##1. array_unique() function

array_unique() function is used to remove duplicate values in an array. If two or more array values are the same, only the first value is retained and the other values are removed.

Note: The retained array will retain the key type of the first array item.

Copy after login

Can the values ​​of an array in php be repeated?

2. array_count_values() function

array_count_values() function can count the number of occurrences of all values in the array; if the number If it is 1, the element is not repeated.

array_count_values() function will return an associative array, the key name of its element is the value of the original array, and the key value is the number of times the value appears in the original array.

         
Copy after login

Can the values ​​of an array in php be repeated?

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of Can the values of an array in php be repeated?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!