note 100898 rejected from function.min by danbrown

From: Date: Sat, 13 Nov 2010 23:17:12 +0000
Subject: note 100898 rejected from function.min by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-174008@lists.php.net to get a copy of this message
Note Submitter: matt at borjawebs dot com ---- 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.

« previous php.notes (#174008) next »