如何统计PHP数组中多个元素值的总字符数用于条件判断
PHP计算数组前三个段落总字符数方案
原代码错误点
- 误用
count_chars()函数:该函数默认返回数组,记录每个ASCII字符的出现次数,无法直接得到字符串总长度,统计总长度应使用strlen() - 数组取值逻辑错误:
$value[0]是取单条段落字符串的首字符,并非取$parts数组的前三个段落元素;PHP中字符串拼接运算符为.,+仅用于数值求和 - 冗余遍历逻辑:无需遍历整个
$parts数组,直接提取数组前三个元素计算即可
修正后代码
<?php $content = '<p>this is p 1</p><p>this is p 2</p><p>this is p 3</p><p>this is p 4</p><p>$test</p>'; $parts = explode('</p>', $content); // 取数组前3个元素 $firstThreeParagraphs = array_slice($parts, 0, 3); // 拼接所有内容后计算总字符数 $totalCharCount = strlen(implode('', $firstThreeParagraphs)); if ($totalCharCount > 40) { echo 'Yep, there are '.$totalCharCount.' characters in the first three paragraphs<br />'; } else { echo 'Nope. There are '.$totalCharCount.' characters in the first three paragraphs<br />'; } ?>
运行说明
示例中前三个段落拼接后的总字符数为45,执行后会输出Yep对应的提示内容。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

