Find key and corresponding value in text file

Asked

Viewed 53 times

0

I have a text file:

0 GATO
1 CACHORRO
2 COELHO
3 RATO

And I want to take 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 he returns me:

"Pussycat".

But if in ID I put 2 it returns:

"Gato 1 Cachorro"

I don’t know if I’m making proper use of these functions PHP

2 answers

1


The flag on $pos must be in false not to 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

Print nothing if not found.

But I think you have more direct and readable 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 scroll through each row of the array of all rows, returned by file('animals.txt');, with each line I divide by space, I keep the array in this format (ex of the first round of the foreach): $params = array(0 => 0, 1 => 'GATO');, then compare the $id we want with each one in position 0 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
  • I drew, the file_get_contents reads the file as a string, while the file reads it as array, that’s what I was looking for anyway! Thanks Miguel!

  • 1

    Exactly @Jacksonantunes. file() return a array, in each element is a line. You are welcome

1

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

$arr = array();

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

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

fclose($file);

var_dump($arr);

Exit:

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 like the ID of the animal:

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

Exit:

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 in some interactive way, you can put the receipt inside the $arr[..numero aqui] and ready.

  • Interesting also your example, I do not know much about the function fopen I’ll do a search later to find out more! Thank you!

  • 1

    briefly fopen = open file :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.