How to Fill in the field when the field is empty in PHP?

Asked

Viewed 440 times

1

The LIMITE_SUPERIOR field is of the real type. I’d like to know how to tell him that if it’s empty fill in the number 0 field and when it’s not empty can fill in the number he found inside the database.

$examesEquipamentos = [];
foreach ($csv as $linha) {
    $examesEquipamentosId = trim($linha['ID']) . '-' . trim($linha['ID_TR']);
    if (!array_key_exists($examesEquipamentosId, $examesEquipamentos)) {
        $examesEquipamentos[$examesEquipamentosId] = [
            'ID' => trim($linha['ID']),
            'NOME_PARAMETRO' => trim($linha['NOME_PARAMETRO']),
            'ID_TR' => trim($linha['ID_TR']),
            'TR_NOME' => trim(mb_strtoupper($linha['TR_NOME'])),
            'UNIDADE_RESULTADO' => trim($linha['UNIDADE_RESULTADO']),
            'CATEGORIA_RESULTADO' => trim($linha['CATEGORIA_RESULTADO']),
            'LIMITE_INFERIOR' => trim($linha['LIMITE_INFERIOR']),
            'LIMITE_SUPERIOR' => trim($linha['LIMITE_SUPERIOR']),
        ];

    }
}
  • I did not understand well, in case it returns null or empty want to be returned 0 ?

  • @Gladiator If he’s a float why are you giving trim() in it? It’s a string, no?

  • he takes the value from the csv. file and this csv has field with filled and empty fields. so at times of returning the empty fields wanted to put zero in place instead of returning me an empty field

4 answers

3

Using a shortened version of ternary operator is readable, simple and concise:

<?php
echo trim("") ?: 0;     // 0
echo trim("2.5") ?: 0;  // "2.5"

Explaining, from PHP 5.3 it is possible to omit the middle part of the ternary operator:

<?php
echo $x ? $x : 0;
// é o mesmo que
echo $x ?: 0;

That is, if the value of $x for Truthy prints $x, else the value after the ?:, which in this case is 0.


Your example would be:

<?php

$examesEquipamentos[$examesEquipamentosId] = [
    // ...
    'LIMITE_SUPERIOR' => trim($linha['LIMITE_SUPERIOR']) ?: 0,
    // ...
];
  • Your answer is good, but it will replace even the field lines that already have values filled. I just want him to fill in the fields that are empty. There’s the problem with your answer

  • Did you test? If trim($linha['LIMITE_SUPERIOR']) is an empty string it fills in, otherwise it does not fill in.

  • 1

    Look here this same code running.

  • 1

    Thanks friend your answer is also GOOD!!! I tested here and it worked. I had put wrong thing before. But your answer and that of the other colleague is right.Thanks for helping me out!!!

  • And how can I only list the rows of the non-empty field ? example 'ID' => Trim($line['ID']), if the id comes empty that jumps and does not list. I am generating an sql script for the csv file. I don’t know if I am at least clear with my friend question.

  • You can use the function array_filter() to remove any unwanted value, see this example. Remember that '0' is false for PHP.

  • I’m sorry but I could not fit this into my code :( although your example was quite clear to me...if you can help I would really appreciate @fernandosavio

  • Just add it after you mount your array or while you actually mount it. Look here.

  • strange but it keeps returning the line with the id field that is empty. even the way I did it anyway.I tried it anyway. I couldn’t understand why

Show 4 more comments

2

You can use an if ternary with Empty to check if it came null, it looks like this.

'LIMITE_SUPERIOR' => empty($linha['LIMITE_SUPERIOR']) ? 0 : trim(empty($linha['LIMITE_SUPERIOR'])
  • i’ll test to see @Renan Keys

  • His response was good, but where he found a value he replaced with zero. I just wanted him to put zero where comes empty and where already has a value that does nothing.

  • The yes I made a Ctrl+C and Ctrl+V had to have removed the Empty() from the second part the Empty returns a boolean so where it had value he was putting 0 because it had content and the return it false or 0 in the case. 'LIMITE_SUPERIOR' => Empty($line['LIMITE_SUPERIOR']) ? 0 : Trim($line['LIMITE_SUPERIOR''])

2


I believe that the simplest way to make it work is by making a conversion, putting (double),(float) or (real) before the value is assigned.

Your code would look like this:

$examesEquipamentos = [];
foreach ($csv as $linha) {
  $examesEquipamentosId = trim($linha['ID']) . '-' . trim($linha['ID_TR']);
  if (!array_key_exists($examesEquipamentosId, $examesEquipamentos)) {
    $examesEquipamentos[$examesEquipamentosId] = [
      'ID' => trim($linha['ID']),
      'NOME_PARAMETRO' => trim($linha['NOME_PARAMETRO']),
      'ID_TR' => trim($linha['ID_TR']),
      'TR_NOME' => trim(mb_strtoupper($linha['TR_NOME'])),
      'UNIDADE_RESULTADO' => trim($linha['UNIDADE_RESULTADO']),
      'CATEGORIA_RESULTADO' => trim($linha['CATEGORIA_RESULTADO']),
      'LIMITE_INFERIOR' => trim($linha['LIMITE_INFERIOR']),
      'LIMITE_SUPERIOR' => (double)$linha['LIMITE_SUPERIOR'], //<-- Conversão aqui.
    ];
  }
}

Documentation here: http://php.net/manual/en/language.types.type-juggling.php

  • the question here is: this LIMITE_SUPERIOR is taking values from a csv and in this csv has lines of the fields LIMITE_SUPERIOR THAT COMES FILLED pq there are values inside the csv files and have lines of this field that are empty. I would simply return 0 when it finds an empty field and when it finds an already filled field it does nothing and leaves this field filled.

  • You tested the code?

  • 1

    vc was right. he put zero only on the empty field lines and the filled fields left as was. Thanks @Laércio Lopes

  • and how can I do to only list the rows of the non-empty field ? example 'ID' => Trim($line['ID']), if the id sees empty it jumps and does not list that line that has the empty id. I am generating an sql script for the csv file. I don’t know if I was at least.

  • It was clear yes, test trim($linha['ID']) if null or empty. Example: https://answall.com/questions/2639/diff%C3%A7a-entre-null-Empty-0-e-false

  • Also: http://www.mauricioprogramador.com.br/posts/verifica-variavel-vazia-php

  • Test before assigning the array.

  • @ Laércio Lopes unfortunately I could not implement this following the example of my code. : ( I don’t know what else to do

Show 3 more comments

0

Try this below:

$examesEquipamentos = [];

$limite_superior = "";
foreach ($csv as $linha) {
if(trim($linha['LIMITE_SUPERIOR']) == null){
        $limite_superior = 0;
}else{
        $limite_superior = trim($linha['LIMITE_SUPERIOR']);
}
$examesEquipamentosId = trim($linha['ID']) . '-' . trim($linha['ID_TR']);
if (!array_key_exists($examesEquipamentosId, $examesEquipamentos)) {
    $examesEquipamentos[$examesEquipamentosId] = [
        'ID' => trim($linha['ID']),
        'NOME_PARAMETRO' => trim($linha['NOME_PARAMETRO']),
        'ID_TR' => trim($linha['ID_TR']),
        'TR_NOME' => trim(mb_strtoupper($linha['TR_NOME'])),
        'UNIDADE_RESULTADO' => trim($linha['UNIDADE_RESULTADO']),
        'CATEGORIA_RESULTADO' => trim($linha['CATEGORIA_RESULTADO']),
        'LIMITE_INFERIOR' => trim($linha['LIMITE_INFERIOR']),
        'LIMITE_SUPERIOR' => trim($limite_superior),
    ];
}

}

  • I’m gonna test @Douglas

  • I could not understand well what your code does. $limite_superior you put it as a variable while in no time it was declared.

  • You can declare off the foreach. I just forgot to declare.

Browser other questions tagged

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