note 89436 modified in function.array-flip by danbrown
| From: | danbrown@php.net | Date: | Sat, 07 Mar 2009 20:49:47 +0000 |
| Subject: | note 89436 modified in function.array-flip by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-151605@lists.php.net to get a copy of this message | ||
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only
retrieve the longest value is unnecessary work. The following should be O(n) instead of O(n log n).
It could also be:
<?php
function get_longest_value($array) {
// Some don't like to initialize, I do
$longest = NULL;
$longestLen = -1;
foreach ($array $value) {
$len = strlen($value);
if($len>$longestLen) {
$longest = $value;
$longestLen = $len;
}
}
$longest = str_replace("\r\n", "\n", $longest);
if (get_magic_quotes_gpc()) { return stripslashes($longest); }
return $longest;
}
?>
--was--
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only
retrieve the longest value is unnecessary work. The following should be O(n) instead of O(n log n).
It could also be:
function get_longest_value($array) {
// Some don't like to initialize, I do
$longest = NULL;
$longestLen = -1;
foreach ($array $value) {
$len = strlen($value);
if($len>$longestLen) {
$longest = $value;
$longestLen = $len;
}
}
$longest = str_replace("\r\n", "\n", $longest);
if (get_magic_quotes_gpc()) { return stripslashes($longest); }
return $longest;
}
http://php.net/manual/en/function.array-flip.php