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.
// 定义一个含有重复键值的数组 $arr = array('apple', 'orange', 'banana', 'apple', 'pear', 'banana'); // 使用 array_unique() 函数去除重复键值,生成一个不重复的数组 $new_arr = array_unique($arr); // 将新数组赋值给旧数组,完成去重 $arr = $new_arr; // 输出不重复的数组 print_r($arr);
Array ( [0] => apple [1] => orange [2] => banana [4] => pear )
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!