How do to "explode" sometimes receive more values?

Asked

Viewed 43 times

2

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

I have the following txt:

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

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

Just follow 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')";

1 answer

3


You will have to process 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 it doesn’t have the fourth value, it will take null.

Or it may return 0 if you don’t want to null and/or its bank:

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

Since you know better than anyone what you have in value, then you can treat it in the best way, examples:

(isset($valor[4]) && $valor[4] > 0) ...
($valor[4] > 0) ...
(strlen($valor[4]) > 0) ...

Browser other questions tagged

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