在《PHP A Beginners Guide》一书中,有这么两道章节练习题:
题一:编写一段PHP脚本,统计一个文件中的文本行数。
我是这样写的
<?php $sum = 0; $arr = file('example.txt') or die('ERROR, file cannot open'); foreach($arr as $line){ $sum++; } echo $sum; ?>
当我看到书中的答案,我大吃一惊,原来代码可以如此简洁。
<?php
echo count(file('example.txt')) . ' line(s) in file.';
?>
题二:编写一段PHP脚本,将文本中的倒置,书中答案如下:
<?php
file_put_contents('reversed.txt', strrev(file_get_contents('example.txt')))
?>
其实想一想,也挺简单的,只不过自己没有想到。