PHP calculates the elements whose three values add up to 0 in an array, which may be a little difficult for some PHP beginners. In fact, it is very simple as long as you understand the calculation idea. Here we need to understand the array_push function in PHP.
Recommended reference study: "PHP Tutorial"
Below we will directly introduce PHP calculations to you with specific code examples. Method for adding three elements in an array to equal 0.
The code example is as follows:
<?php //PHP计算数组中三个值相加等于0的元素 function aaa($arr){ $count = count($arr) - 2; $result=[]; for ($x = 0; $x < $count; $x++){ if($arr[$x]+ $arr[$x+1] + $arr[$x+2] == 0){ array_push($result,"{$arr[$x]} + {$arr[$x + 1]}+{$arr[$x + 2]} =0"); } } return $result; } $arr = array(-1,0,1,2,-1,-4); print_r(aaa($arr));
Here, the elements whose three values in the array $arr add up to 0 are calculated. The result is as follows:
Introduction to related functions:
count function —Calculate the number of units in an array, or the number of attributes in an object.
array_push function—Push one or more cells to the end of the array (push)
array_push ( array &$array , mixed $value1 [, mixed $... ] ) : int
array_push() treats array as a stack and passes in The variable is pushed to the end of the array. The length of array will increase according to the number of variables pushed onto the stack. Has the same effect as:
<?php $array[] = $var; ?>
and repeats the above action for each incoming value.
Note: If you use array_push() to add a unit to the array, it is better to use $array[] =, because there is no additional burden of calling the function.
array_push() will issue a warning if the first argument is not an array. This is different from the behavior of $var[], which creates a new array.
The parameter array represents the input array. value1 represents the first value to be pushed at the end of array.
The return value is the number of elements in the array after return processing.
This article is about PHP's method of calculating the elements whose three values add up to 0 in an array. It's actually very simple. I hope it will be helpful to friends who need it!
The above is the detailed content of PHP calculates the elements in an array whose sum of three values equals 0. For more information, please follow other related articles on the PHP Chinese website!