How do I "explode" sometimes receive more values?

2

I have a code that reads a txt and saves it in the database, but sometimes it will receive more values, eg:

I have the following txt:

|texto|texto|texto|
|texto|texto|texto|texto|

If I use to receive the 4 fields, it gives error in having only 3, what could be done?

Here is my code:

<?php
session_start();
ob_start();

include_once("conexao.php");

$arquivo_tmp = $_FILES['arquivo']['tmp_name'];

$dados = file($arquivo_tmp);

foreach($dados as $linha){
    $linha = trim($linha);
    $valor = explode('|', $linha);

    $REG = $valor[1];
    $COD = $valor[2];
    $UNID = $valor[3];
    $QTD = $valor[4];
    $cod1 = "INSERT INTO temp (REG, COD, UNID, QTD) VALUES ('$REG','$COD_ITEM','$UNID','$QTD')";
    
asked by anonymous 20.08.2018 / 13:27

1 answer

3

You'll have to treat the values, of course, in conjunction with your database.

An example:

$REG = $valor[1];
$COD = $valor[2];
$UNID = $valor[3];
(isset($valor[4])) ? $QTD = $valor[4]: $QTD = NULL;

So, if you do not have the 4th value, it will take null .

Or you can return 0 if you do not want null and / or your bank requires value:

(isset($valor[4])) ? $QTD = $valor[4]: $QTD = 0;

As you know better than all you have in the value, then you can treat the best way, examples:

(isset($valor[4]) && $valor[4] > 0) ...
($valor[4] > 0) ...
(strlen($valor[4]) > 0) ...
    
20.08.2018 / 13:31