There is a file 1.txt with the words:

  • text12
  • text123
  • text1234

    .., etc. (1 word per line)
    idea: read this file into an array, display the total number of lines in the file, further analysis of each word: namely: word output - the number of letters in this word, and you need to show the first and last letter of the word. Without a cycle, everything shows up well, I try with the cycle, it shows everything wrong, help me figure out what's wrong, where my mistake

    $fp = file("1.txt"); echo 'Количество строк в файле: '.count($fp); echo "<hr>"; for ($i = 0; $i <= count($fp); $i++) { $fp = file("1.txt"); $str = trim($fp[i]); $word = $fp[$i]; echo "<hr>".$word."</br>"; echo "Букв:&nbsp; ".iconv_strlen($word)."</br>"; //количество букв в слове echo "Первая:&nbsp; <b>(".$word{0}.")</b>"; //первая буква echo "&nbsp;Последняя:&nbsp; <b>(".substr($word, strlen($word)-1, 1).")</b></br>"; //последняя буква } 

    that's what shows

    Number of lines in the file: 3
    text12
    Letters: 8
    First: (t) Last: ()

    text123
    Letters: 9
    First: (t) Last: ()

    text1234
    Letters: 8
    First: (t) Last: (4)

Letters: 0
First: () Last: ()
It also shows 4 line which is not

  • check the string for emptiness, because this is a normal case - ilyaplot
  • use substr, and even better mb_substr and mb_strlen for utf-8 encoding - ilyaplot
  • count ($ fp) is not clear here. fp is not an array. - ilyaplot
  • The fourth line is the transfer of the line from the third one, it saves trim and checking for emptiness. - u_mulder

1 answer 1

5 line duplicates the first, and even in the loop.

To run through the array is foreach .

in the 6th line, use the $str variable and apply trim() to the value from the array, but in the 7th line, in the $ word variable you add the value from the array not processed trim() again.

in 10 you can use substr($word, 0, 1) .

in 11th you can use substr($word, -1, 1) .