Find key and corresponding value in text file

0

I have a text file:

0 GATO
1 CACHORRO
2 COELHO
3 RATO

And I want to get the id and the corresponding value, for example: when I enter 0 return "Cat" and so on.

$text = file_get_contents('animals.txt');
$id = "1";
$id_str = strlen($id);
$pos = stristr($text, $id, true);
$pos_str = strlen($pos);
$pos_str = ($pos_str - $id_str);
$res = substr($pos, $id_str, $pos_str);
echo $res;

That way it returns me:

  

"Cat".

But if in ID I put 2 it returns:

  

"Cat 1 Dog"

I do not know if I'm doing this correctly using PHP

    
asked by anonymous 14.04.2017 / 11:26

2 answers

1

The flag in $pos must be in false to not include what comes before, taking advantage of your example:

<?php
$text = file_get_contents('animals.txt');
$id = "2";
$id_str = strlen($id);
$pos = stristr($text, $id, false);
$pos_str = strlen($pos);
$pos_str = ($pos_str - $id_str);
$res = substr($pos, $id_str, $pos_str);
echo explode("\n", $res)[0]; // excluir o que vem depois da quebra de linha

Do not print anything if it is not found.

But I think you have more direct and legible ways of doing it, and not so costly. EX:

<?php
$lines = file('animals.txt');
$id = 2;
foreach($lines as $line) {
    $params = explode(' ', $line); // dividir cada linha por espaço, id - valor
    if($params[0] == $id && isset($params[1])) { // ver se é igual e cobrir a hipotese de poder haver linhas sem o valor (segundo elemento de $params)
        $ani = $params[1];
        break;
    }
}
if(isset($ani)) { // se tivermos encontrado o valor relativo ao id
    echo 'Foi encontrado o valor do id ' .$id. ' é: ' .$ani; // COELHO
}
else {
    echo 'Nenhum valor para o id ' .$id; // nao encontramos nenhum valor para aquele id
}

What I did here was to go through each row of the array of all rows, returned by file('animals.txt'); , each row I will divide by space, I get the array in this format (ex from the first loop of the foreach): $params = array(0 => 0, 1 => 'GATO'); , then we compare the $id we want with each one in the 0 position of this array.

If you really want to use file_get_contents :

<?php
$content = file_get_contents('animals.txt');
$lines = explode("\n", $content); // acrescentar esta linha, dividir por quebra de linha para ficar com todas as linhas num array
$id = 2;
// ... O RESTO É IGUAL AO EXEMPLO ACIMA
    
14.04.2017 / 11:39
1

Instead of using file_get_contents() you could also use fopen() .

$arr = array();

$file = fopen('texto.txt', 'r');

while (!feof($file)) {
    $line = fgets($file);
    $arr[] = explode(' ', $line);
}

fclose($file);

var_dump($arr);

Output:

array(4) {
[0] =>
 array(2) {
   [0] =>
   string(1) "0"
   [1] =>
   string(5) "GATO"
}
[1] =>
array(2) {
  [0] =>
  string(1) "1"
  [1] =>
  string(9) "CACHORRO"
}
[2] =>
array(2) {
  [0] =>
  string(1) "2"
  [1] =>
  string(7) "COELHO"
}
[3] =>
array(2) {
  [0] =>
  string(1) "3"
  [1] =>
  string(4) "RATO"
 }
}

Or if you want to use the arrays key as the ID of the animal:

while (!feof($file)) {
    $line = fgets($file);
    $itens = explode(' ', $line);
    $arr[$itens[0]] = $itens[1];
}

Output:

array(4) {
[0] =>
  string(5) "GATO"
[1] =>
  string(9) "CACHORRO"
[2] =>
  string(7) "COELHO"
[3] =>
  string(4) "RATO"
}

echo $arr[0]; // GATO

If the idea is to receive the values by some interactive mode, you can put the receipt inside $arr[..numero aqui] and that's it.

    
14.04.2017 / 15:50