简体   繁体   English

从PHP中的数组中读取最长的字符串 5.3

[英]Read the longest string from an array in PHP 5.3

Here is part of the code.这是代码的一部分。

$DatabaseArray=Array("Cooking","look","I cant","Walking the dog to the park","washing","talk","one");
  
$largest = max($DatabaseArray);
  
echo $largest. "<br />";

I would like to read the longest string from an array in PHP 5.3.0.我想从 PHP 5.3.0 中的数组中读取最长的字符串。 I've tried the max function but doesnt seem to work as expected.我试过最大 function 但似乎没有按预期工作。

$longestEntry = array_reduce($databaseArray, function ($a, $b) { return strlen($a) > strlen($b) ? $a : $b; });

(uses PHP 5.3 syntax) (使用 PHP 5.3 语法)

You can't just use max , since that assumes all entries are numbers.您不能只使用max ,因为它假定所有条目都是数字。 Since they're strings though, "the maximum string" could mean anything, so you have to do manual comparison using strlen .由于它们是字符串, “最大字符串”可能意味着任何东西,因此您必须使用strlen进行手动比较。 The above array_reduce method with custom reduce function does such comparison and reduces the array to the longest member.上面带有自定义reduce function 的array_reduce方法进行了这样的比较,并将数组减少到最长的成员。

If you have a lot of entries (and I mean a lot , hundreds or thousands and up), it may not be very efficient, since it basically applies strlen twice to the whole array.如果您有很多条目(我的意思是很多,数百或数千甚至更多),它可能不是很有效,因为它基本上将strlen两次应用于整个数组。 If that's a problem, this is more efficient by applying strlen only once per string:如果这是一个问题,通过每个字符串只应用一次strlen会更有效:

$longestEntry = current(array_reduce($databaseArray, function ($a, $b) {
    $b = array($b, strlen($b));
    return $a[1] > $b[1] ? $a : $b;
}, array(null, 0)));

Since you're calling it a DatabaseArray though: If this is coming from the database, you should make it do the work.既然你称它为DatabaseArray :如果它来自数据库,你应该让它完成工作。 It's probably going to be even more efficient.它可能会更有效率。 Eg:例如:

SELECT * FROM `table` ORDER BY CHAR_LENGTH(`string_col`) DESC LIMIT 1
$lengths = array_map('strlen', $DatabaseArray);
$maxLength = max($lengths);
$index = array_search($maxLength, $lengths);
echo $DatabaseArray[$index];

Like @deceze's answer, my suggestion is a single pass over the input array.就像@deceze 的回答一样,我的建议是对输入数组进行单次传递。 @KingCrunch's has a greater cost in terms of time complexity because it is using functions to traverse the data more N times. @KingCrunch 在时间复杂度方面的成本更高,因为它使用函数来遍历数据N次。

Below has the same fundamental logic as @deceze's PHP snippet, but uses intuitive, individual variables instead of indexed elements for temporary storage.下面与@deceze 的 PHP 片段具有相同的基本逻辑,但使用直观的单个变量而不是索引元素进行临时存储。

Code: ( Demo )代码:(演示

$maxLength = -1;
$longestValue = null;
foreach ($array as $value) {
    $length = strlen($value);
    if ($length > $maxLength) {
        $maxLength = $length;
        $longestValue = $value;
    }
}
var_export($longestValue);

Output: Output:

'Walking the dog to the park'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM