如何在PHP中输出具有四个或四个以上字母的数组中的元素,并说明它们出现的次数


How to output elements in an array with four or more letters in PHP and state how many times they occur

如何从数组中输出包含四个或四个以上字母的单词,并说明它们出现的次数?

$selection = array("house", "are", "better", "love", "dog",
    "love", "don't", "me", "like", "apples", "frank", "better", "you", 
    "like", "house", "better", "love", "cream");
$array2 = array();
foreach ($selection as $word) {
    if (strlen($word) >= 4) {
        $array2[] = $word;
        print_r(array_count_values($word));
    }
}
return $array2;
foreach ($array2 as $key => $value) {
    printf("The word '$key' appears $value times<br>'n");
}

您的代码中有几个问题。您应该使用单词作为数组键,并保持一个运行计数。

此外,您正在调用return,这将有效地停止脚本。

最后,使用更具描述性的变量名来帮助跟踪您正在做的事情。

<?php
$selection = array("house", "are", "better", "love", "dog",
                   "love", "don't", "me", "like", "apples", "frank", "better", "you", 
                   "like", "house", "better", "love", "cream");
$results = array();
foreach ($selection as $word) {
    if (strlen($word) >= 4) {
        if (array_key_exists($word, $results) == false)
            $results[$word] = 0;
        $results[$word]++;
    }
}
foreach ($results as $word=>$count) {
    print "The word '$word' appears $count times<br>'n";
}
?>

http://codepad.viper-7.com/pq89ic

文档&相关阅读

  • return-http://us1.php.net/return
  • 阵列-http://us1.php.net/manual/en/language.types.array.php
  • 7+1命名变量的技巧关于制作好软件-http://www.makinggoodsoftware.com/2009/05/04/71-tips-for-naming-variables/

这样做:

<?
$selection = array("house", "are", "better", "love", "dog",
    "love", "don't", "me", "like", "apples", "frank", "better", "you", 
    "like", "house", "better", "love", "cream");
$array2 = array();
foreach ($selection as $word) {
    if (strlen($word) >= 4) {
        if (isset($array2[$word])) $array2[$word]++;
            else $array2[$word] = 1;
    }
}
foreach ($array2 as $key => $value) {
    printf("The word '$key' appears $value times<br>'n");
}
?>

见工作代码