Home  >  Article  >  Backend Development  >  How to define a unique array in php

How to define a unique array in php

PHPz
PHPzOriginal
2023-04-26 09:09:24449browse

To define a unique array in PHP, you can use the array_unique() function. This function can remove duplicate key values ​​​​in the array and return a new array. The following is the specific code implementation:

// 定义一个包含重复键值的数组
$arr = array(1, 2, 3, 4, 2, 3, 5);

// 使用 array_unique() 函数去除重复键值
$new_arr = array_unique($arr);

// 输出新数组
print_r($new_arr);

Run the above code, you will get the following output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [6] => 5
)

As you can see, the duplicate key values ​​2 and ## in the array #3 is removed and a new non-duplicate array is generated.

In actual development, if you need to define a non-duplicate array, it is best to remove duplicate key values ​​when the array is initialized to avoid problems in subsequent operations. The following is an example:

// 定义一个含有重复键值的数组
$arr = array('apple', 'orange', 'banana', 'apple', 'pear', 'banana');

// 使用 array_unique() 函数去除重复键值,生成一个不重复的数组
$new_arr = array_unique($arr);

// 将新数组赋值给旧数组,完成去重
$arr = $new_arr;

// 输出不重复的数组
print_r($arr);
Run the above code, you will get the following output:

Array
(
    [0] => apple
    [1] => orange
    [2] => banana
    [4] => pear
)
As you can see, the duplicate key values ​​​​

apple and banana in the array was removed, a new non-duplicate array was generated, and the original array was reassigned into a non-duplicate array.

The above is the detailed content of How to define a unique array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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