Home >Backend Development >PHP Problem >How to remove 0 and duplicate values from php array
Steps to remove 0 and duplicate values from php array: 1. Use the array_diff() function to remove 0 from the array. The syntax "array_diff($arr, [0])" will return an array of 0's; 2 . Use the array_unique() function to delete duplicate values in the 0 array. The syntax is "array_unique($arr)".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php array removal 0 and duplicate values
Step 1: Use the array_diff() function to remove 0 in the array
array_diff() function is used to compare two array values and return the difference set, you only need to use an array containing "0" to compare with the original array
Syntax:array_diff($arr, [0])
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,0,1,"a","b","c",0,"d","a","c"); echo "原数组:"; var_dump($arr); $arr = array_diff($arr, [0]); echo "去除0后:"; var_dump($arr); ?>
Step 2: Use array_unique() to delete duplicate values in the 0 array
array_unique() function removes the duplicate values in the array Duplicate values and return the resulting array.
When the values of several array elements are equal, only the first element is retained and the other elements are deleted.
<?php header('content-type:text/html;charset=utf-8'); $arr=array(1,2,3,0,1,"a","b","c",0,"d","a","c"); $arr = array_diff($arr, [0]); echo "去除0后:"; var_dump($arr); echo "去除重复值后:"; var_dump(array_unique($arr)); ?>
Description:
array_diff()
The function is used to compare two (or more ) value of the array and returns the difference set.
This function compares the values of two (or more) arrays (key=>value in value), and returns a difference array, which includes all the arrays being compared (array1 ), but not in any other parameter array (array2 or array3, etc.).
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove 0 and duplicate values from php array. For more information, please follow other related articles on the PHP Chinese website!