How to duplicate arrays and sum them in php

青灯夜游
Release: 2023-03-15 21:46:01
Original
2324 people have browsed it

Methods for deduplicating arrays and summing: 1. Use array_unique() to deduplicate, syntax "array_unique(array)", return a new array without duplicate values; 2. Use array_sum() to perform summation , the syntax "array_sum (array after deduplication)" returns the sum of all values ​​in the deduplication array.

How to duplicate arrays and sum them in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php deduplication array The sum can be implemented in two steps:

Step 1. Use the array_unique() function to deduplicate the array

array_unique( ) function is used to remove duplicate values ​​from 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.

<?php 
header("content-type:text/html;charset=utf-8");
$array = array(1,2,3,3,4,2,3,5,6,4,5,7,8,9,10); 
var_dump($array);       
 
$result = array_unique($array);
echo "删除重复元素后的数组";
//var_dump(array_values($filtered_array)); 
var_dump($result);
?>
Copy after login

How to duplicate arrays and sum them in php

Step 2, use array_sum() to find the sum

$sum=array_sum($result);
echo "数组去重后求和:".$sum;
Copy after login

How to duplicate arrays and sum them in php

Description:

array_sum($arr) The function is used to calculate the sum of all elements in the array

  • If all elements of the array arr are integers , returns an integer value; if one or more of the values ​​is a floating-point number, a floating-point number is returned.

  • If there are non-numeric elements in the array arr, PHP will try to convert them to a numeric value, and if the conversion fails, it will be treated as a 0 value.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to duplicate arrays and sum them in php. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template