-2

在 PHP foreach 循环中,我有一个人的名字循环。但是,在循环之外,我想确定循环内使用的最大长度。所以我在循环中可能有 6 个名字,其中大多数可能是 6-8 个字符长,但一个可能是 12 个字符。所以我想找到最大的数量。

4

3 回答 3

2
$longest = '';
foreach($names as $name) {
    if(strlen($name) > strlen($longest)) {
        $longest = $name;
    }
}
于 2013-01-27T13:09:27.973 回答
1

作为更明显的变体,考虑一个功能实现:

$longest = array_reduce($names, function($longest, $candidate) {
    return strlen($longest) >= strlen($candidate) ? $longest : $candidate;
});
于 2013-01-27T13:13:04.083 回答
0
$info = array();

$names = array("Name 1","Name 2","Name 3","This is the longest string","Name 4");

foreach($names as $key=>$value) {
    if(empty($info) || strlen($value) > $info[1]) {
        $info[0] = $key;
        $info[1] = strlen($value);
    }
}

echo 'The longest value is ', $names[$info[0]], ' which has ', $info[1], ' charachters and its array index is ', $info[0];
于 2013-01-27T13:13:57.030 回答