note 100898 added to function.min

From: Date: Sat, 13 Nov 2010 21:12:41 +0000
Subject: note 100898 added to function.min
Groups: php.notes 
Request: Send a blank email to php-notes+get-174005@lists.php.net to get a copy of this message
There is a flaw in this example where two elements may contain the same value. During an array_flip, there is currently no way given to discriminate between (or together) that both indices 2 and 4 contain the lowest value 13: $arSrc[0]=14; $arSrc[1]=16; $arSrc[2]=13; $arSrc[3]=17; $arSrc[4]=13; $iMinValue = min($arSrc); $arFlip = array_flip($arSrc); $iMinPosition = $arFlip[$iMinValue]; echo '<br />min_value=', $iMinValue, '<br />min_position=', $iMinPosition ; This returns index 4. The best way to approach this would be to get the min value, throw the source array back into a foreach() loop, noting each element that contains the same minimum value and then come up with a tie breaker function to choose one element over the other. For example: $min_keys = array(); $iMinValue = min($arSrc); foreach($arSrc as $index => $value) { if($value == $iMinValue) array_push($min_keys, $index); } // do something with $min_keys, an array containing all element keys from $arSrc that share the same minimum value. ---- Server IP: 69.147.83.197 Probable Submitter: 67.61.92.55 ---- Manual Page -- http://www.php.net/manual/en/function.min.php Edit -- https://master.php.net/note/edit/100898 Del: integrated -- https://master.php.net/note/delete/100898/integrated Del: useless -- https://master.php.net/note/delete/100898/useless Del: bad code -- https://master.php.net/note/delete/100898/bad+code Del: spam -- https://master.php.net/note/delete/100898/spam Del: non-english -- https://master.php.net/note/delete/100898/non-english Del: in docs -- https://master.php.net/note/delete/100898/in+docs Del: other reasons-- https://master.php.net/note/delete/100898 Reject -- https://master.php.net/note/reject/100898 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#174005) next »