★ wanayoo — archive 1999 http://fr.php.net/manual/ja/function.array-reduce.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<array_randarray_reverse>
view the version of this page
Last updated: Wed, 09 Mar 2005

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce --  コールバック関数を用いて配列を普通の値に変更することにより、 配列を再帰的に減らす

説明

mixed array_reduce ( array input, callback function [, int initial])

array_reduce()は、配列input の各要素にfunction関数を繰り返し適用し、 配列を一つの値に減らします。オプションintial が利用可能な場合、処理の最初で使用されたり、配列が空の場合の最終結果 として使用されます。

例 1. array_reduce()の例

<?php
function rsum($v, $w) {
  
$v += $w;
   return
$v;
}

function
rmul($v, $w) {
  
$v *= $w;
   return
$v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?>

これにより、$bの値は15 となり、$cの値は 1200 (= 1*2*3*4*5*10)、そして、 $dの値は1となります。

array_filter(), array_map()も参照下さい。



add a note add a note User Contributed Notes
array_reduce
bishop
01-May-2004 05:19
Count the total number of characters in an array of strings:

<?php
$lines
= array ('abc', 'd', 'ef');
$totalChars = array_reduce($lines, create_function('$v,$w','return $v + strlen($w);'), 0);
// $totalChars === 6
?>
tonicpeddler at aol dot com
02-Nov-2002 04:17
in response to php dot net at cuntbubble dot com

actually when you pass a value to a function that accepts a specific data type, php automatically evaluates that value as the data type expected
php dot net at cuntbubble dot com
18-Jan-2002 05:08
There is an error/misleading item in the documentation

[, int initial]

int is not constrained to an integer, it can be any data type (although I've not tested ALL data types)

and $v is the cumulative part, the current value of the reduction.

and I'll take the liberty to add another example, as used in my code

<?php
function reduceToTable($html, $p) {
  
$html .= "<TR><TD><a href=/old?u=http%3A%2F%2Ffr.php.net%2Fmanual%2Fja%2F%5C&y=1999"$p.html\">$p</a></td>\n";
   return
$html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable", "<table>\n");
echo
$tab . "</table>\n";
?>

hmm, getting stuff on one line sure is tricky, it get's wordwrapped on the char count in html so &gt; counts as 4 chars not one so by the time you've counted "< you've used up 8 chars
If it get's through moderation could someone please make it look ok :)

<array_randarray_reverse>
 Last updated: Wed, 09 Mar 2005
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Fri Mar 18 05:13:58 2005 CET