PHP中最短/最长的字符串数组

时间:2010-09-14 22:58:17

标签: php arrays string string-length

我有像这样的数组

$data = array(
    "163",
    "630",
    "43",
    "924",
    "4",
    "54"
);

如何根据字符串长度非数字值从中选择最小值和最大值(对于此示例,它是1(最小)和3(最大)

6 个答案:

答案 0 :(得分:49)

好像你应该使用 array_map()

  // Convert array to an array of string lengths
$lengths = array_map('strlen', $data);

  // Show min and max string length
echo "The shortest is " . min($lengths) .
     ". The longest is " . max($lengths);

请注意,$lengths数组未排序,因此您可以轻松检索每个字符串长度的相应数字。

答案 1 :(得分:4)

以下是brian_d's code的改进版本:

$min = PHP_INT_MAX;
$max = -1;

foreach ($data as $a) {
    $length = strlen($a);
    $max = max($max, $length);
    $min = min($min, $length);
}

答案 2 :(得分:3)

虽然在这种情况下它是不可取的,因为你将遍历数组两次,你也可以使用array_reduce来比较每个元素与其余元素。像这样:

<?php

$data = array('163','630','43','42','999','31');
//Will return the longest element that is nearest to the end of the array (999)
//That's why we use strlen() on the result.
$max_l = strlen(array_reduce($data,'maxlen'));
//Will return the shortest element that is nearest to the end of the array (31)
$min_l = strlen(array_reduce($data,'minlen'));

echo "The longest word is $max_l characters, while the shortest is $min_l\n";

function maxlen($k,$v) {
        if (strlen($k) > strlen($v)) return $k;
        return $v;
}
function minlen($k,$v) {
        if ($k == '') return PHP_INT_MAX;
        if (strlen($k) < strlen($v)) return $k;
        return $v;
}
?>

如果您使用的是PHP 5.3.0+,则可以利用closures

<?php
   $max_l = strlen(array_reduce($data,
                function ($k,$v) { return (strlen($k) > strlen($v)) ? $k : $v; }
        ));

   $min_l = strlen(array_reduce($data,
                function ($k,$v) {
                        if (!$k) return PHP_INT_MAX;
                        return (strlen($k) < strlen($v)) ? $k : $v;
                }
        ));

echo "The longest word is $max_l characters, while the shortest is $min_l\n";
?>

答案 3 :(得分:2)

$min = 100;
$max = -1;

foreach($data as $a){
  $length = strlen($a);
  if($length > $max){ $max = $length; }
  else if($length < $min){ $min = $length; }
}

答案 4 :(得分:1)

<?php
$array = array(
    "163",
    "630",
    "43",
    "924",
    "4",
    "54"
);
$arraycopy  = array_map('strlen',$array);
asort($arraycopy);

$min = reset($arraycopy);

//if you need a single 'minword'
$minword = $array[key($arraycopy)];
//if you need them all
$minwords = array_intersect_key($array,array_flip(array_keys($arraycopy,$min)));


$max = end($arraycopy);
//if you need a single 'maxword'
$maxword = $array[key($arraycopy)];
//if you need them all:
$maxwords = array_intersect_key($array,array_flip(array_keys($arraycopy,$max)));

var_dump($min,$max,$minword,$maxword,$minwords,$maxwords);

答案 5 :(得分:0)

为完成起见,这是最大和最小的单线:

$maximum = max(array_map('strlen', $array));
$minimum = min(array_map('strlen', $array));