PHP is reading the last array key

Asked

Viewed 59 times

0

I have a file . Ret of which returns me as follows:

10400000
2090183800001990000000000000000000001234204321000000000EMPRESA
C ECON FEDERAL 20601201405551100162204000000 RETURN-PRODUCTION 000 10400011T0100030

I put only a stretch, because it is great. To remove the spaces, I did so:

$arquivo = file($_FILES["Arquivo"]["tmp_name"]);
$arquivo = preg_replace('/\s+/', '', $arquivo);

foreach($arquivo as $linhasNum => $linhas) {
  $testes = substr($arquivo[$linhasNum],63,19);
}
echo $testes;

When I give a print_r() in the $file variable, it returns me:

Array ( [0] => 104000002090183800001990000000000000000000001234204321000000000EMPRESACECONFEDERAL20601201405551100162204000000RETORNO-PRODUCAO000 [1] => 10400011T010003020090183800001990000000000000000000001234204321000000000EMPRESA0000162206012014000000000000 [2] => 1040001300001T060000000432100000000240000000111369979100000000000000002012014000000000008000000010860000000000000000090000000000000000000000000000125020101

Up to the key [21] which is the last. The problem is that in the test, it is returning me only this last key and not in order for me to get the correct values. I don’t know if I could make you understand, but how do I make the loop go through all the keys in order and not just take the last one?

  • 2

    In the loop you have to concatenate $testes .= substr($arquivo[$linhasNum],63,19);

  • Thank you Leo....

  • But the problem is the same, All that was said here is what I commented on the previous one. And worse, you are removing the spaces with preg_replace, then you will misalign everything and disturb your SUBSTR. It was better the code of the previous.

  • Hello Bacco. Actually not exactly the same doubt. The first was in trying to read the file the way it comes from the bank. I tried to apply the past solution, but I thought it best to remove the spaces to facilitate development. So it was done, but in this post, the problem is that when removing the spaces, I was only reading the last key and I really forgot to put the $tests = "" and concatenate into the $tests loop .= substr(); to solve the problem. I thought it best to open a new topic, as I understood that they are differentiated problems.

1 answer

0


Within the foreach() he is defining the variable $teste at each loop, then only the last value would be returned in the echo after the loop, try this way:

$arquivo = file($_FILES["Arquivo"]["tmp_name"]);
$arquivo = preg_replace('/\s+/', '', $arquivo);
$testes='';
foreach($arquivo as $linhasNum => $linhas) {
  $testes .= substr($arquivo[$linhasNum],63,19);
}
echo $testes;

Browser other questions tagged

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