array_product
(PHP 5 >= 5.1.0, PHP 7)
array_product — Вычислить произведение значений массива
Описание
array_product() возвращает произведение значений массива.
Список параметров
-
array
-
Массив.
Возвращаемые значения
Возвращает произведение как тип integer или float.
Список изменений
Версия | Описание |
---|---|
5.3.6 | Результатом произведения пустого массива теперь является 1, тогда как ранее данная функция возвращала 0. |
Примеры
Пример #1 Примеры использования array_product()
<?php
$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";
?>
Результат выполнения данного примера:
product(a) = 384 product(array()) = 1
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения, относящиеся к переменным и типам
- Массивы
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_exists
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- each
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
Коментарии
This function can be used to test if all values in an array of booleans are TRUE.
Consider:
<?php
function outbool($test)
{
return (bool) $test;
}
$check[] = outbool(TRUE);
$check[] = outbool(1);
$check[] = outbool(FALSE);
$check[] = outbool(0);
$result = (bool) array_product($check);
// $result is set to FALSE because only two of the four values evaluated to TRUE
?>
The above is equivalent to:
<?php
$check1 = outbool(TRUE);
$check2 = outbool(1);
$check3 = outbool(FALSE);
$check4 = outbool(0);
$result = ($check1 && $check2 && $check3 && $check4);
?>
This use of array_product is especially useful when testing an indefinite number of booleans and is easy to construct in a loop.
You can use array_product to calculate the factorial of n:
<?php
function factorial( $n )
{
if( $n < 1 ) $n = 1;
return array_product( range( 1, $n ));
}
?>
If you need the factorial without having array_product available, here is one:
<?php
function factorial( $n )
{
if( $n < 1 ) $n = 1;
for( $p++; $n; ) $p *= $n--;
return $p;
}
?>
array_product() can be used to implement a simple boolean AND search
<?php
$args = array('first_name'=>'Bill','last_name'=>'Buzzard');
$values[] = array('first_name'=>'Brenda','last_name'=>'Buzzard');
$values[] = array('first_name'=>'Victor','last_name'=>'Vulture');
$values[] = array('first_name'=>'Bill','last_name'=>'Blue Jay');
$values[] = array('first_name'=>'Bill','last_name'=>'Buzzard');
$result = search_for($values,$args);
var_dump($result);exit;
function search_for($array,$args) {
$results = array();
foreach ($array as $row) {
$found = false;
$hits = array();
foreach ($row as $k => $v) {
if (array_key_exists($k,$args)) $hits[$k] = ($args[$k] == $v);
}
$found = array_product($hits);
if (!in_array($row,$results) && true == $found) $results[] = $row;
}
return $results;
}
?>
Output:
array (size=1)
0 =>
array (size=2)
'first_name' => string 'Bill' (length=4)
'last_name' => string 'Buzzard' (length=7)
Here's how you can find a factorial of a any given number with help of range and array_product functions.
function factorial($num) {
return array_product(range(1, $num));
}
printf("%d", factorial(5)); //120
You can use array_product() to calculate the geometric mean of an array of numbers:
<?php
$a = [ 1, 10, 100 ];
$geom_avg = pow( array_product( $a ), 1 / count( $a ));
// = 9.999999999999998 ≈ 10
?>
Just a little correction for Andre D's answer: "(bool) array_product($array);" is equivalent with the conjunction of each array elements of $array, UNLESS the provided array is empty in which case array_product() will return 1, which will translate to boolean TRUE.
To mitigate this, you should expand the function with an additional check:
<?php
$result = !empty($check) && !!array_product($check);
?>