Check if array () is empty with PHP

4

I have a form with several fields. To get the values, I'm doing it this way (I put only the first 4):

<?php
  $dados[0] = $_POST["TipoSanguineo"];
  $dados[1] = $_POST["PlanoSaude"];
  $dados[2] = $_POST["CalendarioVacinal"];
  $dados[3] = $_POST["NomeContato"];
  $dados[4] = $_POST["FoneContato"];

  $metodos->cadastrarFichaMedica(array($dados));
?>  

To redeem the values, I do this:

<?php
...
public function cadastrarFichaMedica($dados){

   for($i = 0; $i < count($dados); $i++){  

       $tipoSanguineo = $dados[$i][0];
       $planoSaude = $dados[$i][1];
       $calendarioVacinal = $dados[$i][2];
       $nomeContato = $dados[$i][3];
       $telefone = $dados[$i][4];
   }
     mysqli_query($this->conexao,"INSERT....");
}

Only the form fields are not mandatory and I would like to know how I can do that, in case the user does not fill in any fields, do not register, that is, check if there are any fields filled out. I tried to use the count () , but even though all the fields are empty, it always returns me value 1. See:

array(1) { [0]=> array(31) { [0]=> NULL [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" [4]=> string(0) "" [5]=> string(0) "" [6]=> string(0) "" [7]=> string(0) "" [8]=> NULL [9]=> NULL [10]=> string(0) "" [11]=> NULL [12]=> NULL [13]=> NULL [14]=> NULL [15]=> NULL [16]=> NULL [17]=> NULL [18]=> NULL [19]=> NULL [20]=> NULL [21]=> NULL [22]=> NULL [23]=> NULL [24]=> NULL [25]=> NULL [26]=> NULL [27]=> NULL [28]=> NULL [29]=> NULL [30]=> NULL } }
    
asked by anonymous 18.09.2018 / 17:44

4 answers

6

Many things do not make sense in your code.

At least considering only the excerpt you posted in the question, it will be up to you to evaluate at the end as only you have access to the rest of the project.

Converting an array into array ...

$dados[0] = $_POST["TipoSanguineo"];
$dados[1] = $_POST["PlanoSaude"];
$dados[2] = $_POST["CalendarioVacinal"];
$dados[3] = $_POST["NomeContato"];
$dados[4] = $_POST["FoneContato"];

$_POST is a PHP superglobal, defined by the interpreter itself, of the associative array type fed with the data that comes through the HTTP request. What you're doing here is basically converting an associative array to another array , only numeric. Both do not make sense: create another array from an array and pass associative to a numeric (if for some reason you do not need the keys, use array_values ).

Do not you think it's much more readable to $nome = $dados['nome'] than $nome = $dados[0] ?

Converting an array to array ... again!

After defining the array $dados from $_POST , you pass it by parameter to cadastrarFichaMedica :

$metodos->cadastrarFichaMedica(array($dados));

But again, you created another array from an array , but now even more serious: you created an array in> array . If your $dado is ['Anderson', 42] , the method will receive as [['Anderson', 42]] , which makes no sense at all.

Incidentally, this is why count always returns 1, because your input array will always be an array with a value, which is a array .

Walk through the array and ... do nothing?

for($i = 0; $i < count($dados); $i++){  
   $tipoSanguineo = $dados[$i][0];
   $planoSaude = $dados[$i][1];
   $calendarioVacinal = $dados[$i][2];
   $nomeContato = $dados[$i][3];
   $telefone = $dados[$i][4];
}

Here you are iterating over your array . Since it is erroneously an array array, accessing the values of the form $dados[$i][0] ends up working. The question here is: you are getting all the values that came through the request into distinct variables and ... you just did nothing with them.

You seemingly run INSERT out of the loop and this will cause only the last iterated record to be inserted. Since your array has only one value, it would not even make a difference, and hopefully it would produce the expected result, but it does not make sense at all.

Finally ... the filter

As the rbz replied, you can use the array_filter to delete unwanted values. Basically your code could be something like:

<?php

$dados = array_filter($_POST);
$metodos->cadastrarFichaMedica($dados);

Where the cadastrarFichaMedica method would be:

public function cadastrarFichaMedica(array $dados){

   $nomeContato = $dados['NomeContato'];
   ...

   mysqli_query($this->conexao,"INSERT....");
}

Obviously, since you will not be able to predict which fields the user will fill out, you should check each one for them.

    
18.09.2018 / 18:29
7

Solution 1

One way to do this would be to use foreach and empty with condition ( if ):

$array = array( 0 => 'aa', 1 => 'bbb', 2 => null, 3 => 'ddd', 4 => null);

foreach ($array as $k => $v) {

    if (empty($v)) echo 'vazio';
    else echo 'não vazio';
    echo '<br>';    
}

Output:

não vazio
não vazio
vazio
não vazio
vazio

See working at ideone

Solution 2

As stated by @AndersonCarlosWoss , using array_filter and empty .

There are several ways, see 3 different examples ( $arrayf1 , $arrayf2 , $arrayf3 ):

$array = array( 0 => 'aa', 1 => 'bbb', 2 => null, 3 => 'ddd', 4 => null);

$arrayf1 = array_filter($array, function($v){if(!empty($v)) return true;});
$arrayf2 = array_filter($array, function($v){return !empty($v);});
$arrayf3 = array_filter($array);

Output of 3:

Array
(
    [0] => aa
    [1] => bbb
    [3] => ddd
)

See working at ideone

Documentation

empty

array_filter

    
18.09.2018 / 17:52
5

I'll leave this answer here as a complement to Comrade @biz's response.

Your count returns true because your array has 31 elements, even though the content of each element is an empty array.

You can check if a variable is empty in several ways, but you may want to define what you consider to be an empty variable.

View the possible values of an empty variable:

  

false

     

array() array without elements

     

0 integer zero

     

"0" string with the number 0

     

null

     

"" an empty string

The function that covers the greatest range of possibilities is the function empty

empty($variavel)

But you can use other functions as you need them. See the return of each function:

  

empty returns true if the variable is false array() 0 "0" null

     

is_null only returns true if the variable is null

     

isset returns true if the variable is set, that is if it is not null

Function documentation:

empty
is_null isset

    
18.09.2018 / 18:33
4

In addition to the solutions presented by @rbz, you can create a method as suggested below to check your data array and receive a Boolean return to validate the omission of data in the submission.

<?php

$dadosCompletos = [
    'nome' => "Usuario",
    'idade' => 99,
    'cidade' => "Sao Paulo",
];

$dadosParciais = [
    'nome' => null,
    'idade' => "",
    'cidade' => "Rio de Janeiro",
];

function possuiCamposVazios(array $arrayCampos): bool {
    $filtro = array_filter($arrayCampos);
    $dif = array_diff($arrayCampos, $filtro);

    return count($dif) === 0 ? false : true;
}

Testing:

var_dump(possuiCamposVazios($dadosCompletos));
var_dump(possuiCamposVazios($dadosParciais));

Output:

bool(false)
bool(true)

As recommended by the staff, reevaluate how you are submitting the form, use the validations on the client with HMTL5 features etc. You can also use some library to validate on the server side if the application becomes more complex.

Test the online code at: link

    
18.09.2018 / 20:23