note 91437 added to function.max

From: Date: Wed, 10 Jun 2009 07:34:30 +0000
Subject: note 91437 added to function.max
Groups: php.notes 
Request: Send a blank email to php-notes+get-156715@lists.php.net to get a copy of this message
sumeruter stated that max() would return the subarray containing the highest value. http://php.net/manual/en/function.max.php#87547 This is not correct. The decision of max() is made according to the *first* element within the first nested array. An example, borrowed from sumeruter: <?php $depth3=array( array(array(1,6,3),array(7,2,5),array(9,3,0)), array(array(2,1,8),array(4,4,5),array( 99 ,6,7)), array(array(0,3,2),array(5,91,11),array(42,25,12))); // it is indeed 99 echo max(max(max($depth3))); ?> The same example, slightly modified: <?php // I just switched the first value of the nested arrays $depth3=array( array(array(2,6,3),array(7,2,5),array(9,3,0)), array(array(1,1,8),array(4,4,5),array( 99 ,6,7)), array(array(0,3,2),array(5,91,11),array(42,25,12))); // Whoops, this echoes 9 echo max(max(max($depth3))); ?> This is because in the first nested max(), the function decides that 2 > 1 > 0 and returns the array array(array(2,6,3),array(7,2,5),array(9,3,0)) which doesn't contain our highest value. For this purpose, better use array_walk_recursive(). http://php.net/manual/en/function.array-walk-recursive.php ---- Server IP: 81.223.48.75 Probable Submitter: 62.99.199.203 ---- Manual Page -- http://www.php.net/manual/en/function.max.php Edit -- https://master.php.net/note/edit/91437 Del: integrated -- https://master.php.net/note/delete/91437/integrated Del: useless -- https://master.php.net/note/delete/91437/useless Del: bad code -- https://master.php.net/note/delete/91437/bad+code Del: spam -- https://master.php.net/note/delete/91437/spam Del: non-english -- https://master.php.net/note/delete/91437/non-english Del: in docs -- https://master.php.net/note/delete/91437/in+docs Del: other reasons-- https://master.php.net/note/delete/91437 Reject -- https://master.php.net/note/reject/91437 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#156715) next »