How to correctly implement a test task for the position of PHP developer?

Question:

HR manager gave a test task. I did. In response, he said that

I received only a brief feedback – I did not like the quality and style of implementation.

I want your advice, what I wrote wrong. Here is the task:

Тестовое задание #1:

Версии ПО: PHP 5.3-5.6

Необходимо реализовать функцию, которая произведет чтение данных файла и вернет обработанные данные в указанном виде.

Функция должна:
 - Считать данные с файла
 - Разбить данные по строкам в массив
 - Отфильтровать массив таким образом, чтобы в нем остались лишь строки содержащие только числа
 - Суммировать числа в каждой строке
 - Отсортировать полученные суммы в порядке убывания
 - Вернуть результат

Пример кода:

     # Путь к файлу данных  $file = __DIR__ . '/datalist.txt'; 
     # Передаем данные в функцию и получаем результат  $result = getResult( $file ); 
     # Отображаем результат  echo '<pre>'; 
     var_export( $result );

      function getResult ( $file )  {
          # @TODO Реализовать...  }

     Пример результата работы функции:  array (    82 => 16396,    19 =>
     16169,    71 => 15864,    73 => 15224,    81 => 14244    ...

Piece of datalist.txt file:

55 NTfy 591 405 kLj 48 644 768 164 ubd 837 oTft GPQV 163 ja 445 961
431 574 168
375 380 427 670 610 284 765 48 687 660 377 333 914 70 146 328 301 925 266
620 237 137 584 427 308 939 660 917 59 864
j hHo 279 tqpg 617 870 CoNJ 173 czgW 301 299 134 820 625 U 369 165 hutPN jiq 31 575 46 NS 397 378 954 764

How I implemented it:

<?php

# Путь к файлу данных
$file = __DIR__ . '/datalist.txt';
# Передаем данные в функцию и получаем результат
$result = getResult($file);
# Отображаем результат
echo '<pre>';
var_export($result);

function getResult($file) {
#Считать данные с файла.
#Разбить данные по строкам в массив
    $line = file($file);
    $i = 0;
    foreach ($line as $value) {
        $ArrayLine = explode(' ', $value);
        foreach ($ArrayLine as $Record) {
            $result[$i] = 0;
#Отфильтровать массив таким образом, чтобы в нем остались лишь строки содержащие только числа
            $CheckString = preg_replace('~[^A-Za-z]+~', '', $Record);
            if (strlen($CheckString) > 0) {
                unset($result[$i]);
                break;
            };
            $res = (int) $Record;
#Суммировать числа в каждой строке
            $result[$i] += $res;
        }
        $i++;
    }
#Отсортировать полученные суммы в порядке убывания
    arsort($result);
    return $result;
}

Answer:

Code

<?php

/**
 * Функция производит чтение данных из файла и возвращает обработанные данные согласно алгоритму
 * - Считать данные с файла
 * - Разбить данные по строкам в массив
 * - Отфильтровать массив таким образом, чтобы в нем остались лишь строки содержащие только числа
 * - Суммировать числа в каждой строке
 * - Отсортировать полученные суммы в порядке убывания
 * - Вернуть результат
 *
 * @param string $file
 * @return array
 */
function getResult($file) {
    $numbers = [];

    $handle = @fopen($file, 'r');
    if ($handle) {
        // Читаем файл построчно
        while (($buffer = fgets($handle, 4096)) !== false) {
            // Удаляет пробелы (или другие символы) из начала и конца строки
            $buffer = trim($buffer);

            if (preg_match('/^[\d ]+$/', $buffer)) {
                // Разбиваем строку на числа, складываем получившийся массив чисел и записываем в массив
                $numbers[] = array_sum(explode(' ', $buffer));
            }
        }
    }

    // Сортируем массив по возрастанию (без сохранения отношений с ключами)
    rsort($numbers);

    return $numbers;
}

$result = getResult(__DIR__ . '/datalist.txt');

print_r($result);

Code comments:

  • According to the input file, in the example, I draw the following conclusion. The function is designed taking into account that the numbers are only positive and integer, and there are no numbers inside the words, for example, oT89ft. And a number cannot go next to a word, for example, 200NTfy (that is, will it be considered a number after the removal of "non-numbers").
  • Although the algorithm contains the step Split data by rows into an array , it is skipped so as not to "fill" the memory (there was no memory overflow). Because there can be a lot of lines in a file. Reading occurs line by line and the sum is immediately calculated and written to the array.
  • The length of the string when reading is limited to length - 1 байт
  • I didn’t “get paranoid”: I sort the array with a built-in PHP function and didn’t create any kind of composer package with tests.
  • Comments in Russian… Preferably in English. write if the company does not mind where you will work – then it will come in handy 🙂

Additional Information

When writing (formatting code), I try to follow the PHP Standards Recommendations , in particular:

Study the information on the site – it will come in handy.

And always contact and study information on PHP on the official website . Documentation in Russian or English. languages.

And don't be afraid to make mistakes! Ask any questions on Stack Overflow!

Scroll to Top