Check that the array() is empty with PHP

Asked

Viewed 13,602 times

4

I have a form with several fields. To get the values, I am doing 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 so:

<?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 that the form fields are not mandatory and I would like to know how to do, if the user does not fill in any field, do not register, that is, check if there are any field filled. I tried to use the Count(), but even though all 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 } }
  • 1

    Out of curiosity, how is your HTML? The code you put last is very strange and does not seem to be a common post. Does your form have 31 fields? Strange that they came as a numerical array, including.

4 answers

8

First of all, beware of the empty, because it can fool you depending on the amounts used.

Value Returned

Returns FALSE if var exists and is not empty and does not contain a value zeroed. Otherwise return TRUE.

What is seen below is considered empty:

"" (an empty string)

0 (0 as an integer)

0.0 (0 as a floating point)

"0" (0 as a string)

NULL

FALSE

array() (an empty array)

$var; (a declared variable but no value)

(documentation: Empty)


Solution 1

Counting empty with array_walk_recursive:

$vazios = 0;
array_walk_recursive($array, function($v,$k) use (&$vazios) {
    if (empty($v)) $vazios++;
});

This way you will count the voids, falses, 0, etc.

Solution 2

One way to do it would be by using foreach and empty in good faith (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>';    
}

Exit:

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

See working on ideone


Solution 3

As said by @Andersoncarloswoss, using array_filter and empty.

There are several forms, 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);

Exit of 3:

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

See working on ideone


Documentation

Empty

array_filter

8


A lot of things don’t make sense in your code.

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

Converting an array into an array...

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

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

You don’t think it’s much more readable to do $nome = $dados['nome'] than $nome = $dados[0]?

Converting an array into an 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 a array, only now even more serious: you have created a array of array. If your $dado were ['Anderson', 42], the method will receive as parameter [['Anderson', 42]], which makes no sense at all.

In fact, that’s why the count always returns 1, because its array entry will always be a array with a value, which perhaps 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 on your array. As he is, erroneously, a array of array, access the values of the form $dados[$i][0] ends up working. The question here is, are you getting all the values that came by requesting different variables and... just did nothing with them.

You apparently execute the INSERT out of the loop and this will cause only the last iterated record to be inserted. As your array has only one value even, it would not even make a difference and, with luck, would produce the expected result, only that it does not make any sense.

Finally... the filter

Like the Rbz answered, you can use the function array_filter to delete unwanted values. Basically your code could be something like:

<?php

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

Where the method cadastrarFichaMedica would be:

public function cadastrarFichaMedica(array $dados){

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

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

Obviously, as you will not be able to predict which fields the user will fill in, you should check the existence of each of them.

  • 1

    "Teacher corrects question and answer." + 1.

  • Hello Anderson. In fact the form has more than 30 fields and I confess that I completely forgot about this native function, because I work very little with arrays. Thank you!

5

I will leave this reply here as a complement to comrade @Rbz’s reply.

Your count returns true because its array has 31 elements, although the content of each element is an empty array.

You can check if a variable is empty in several ways, but you should define what you consider as an empty variable.

See possible values of an empty variable:

false

array() array without elements

0 integer zero

"0" string with number 0

null

"" an empty string

The function covering the widest range of possibilities is theempty

empty($variavel)

But you can use other functions as needed.
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, i.e. null


Documentation of functions:

Empty
is_null
isset

  • 1

    Boooa! @Andersoncarloswoss was telling me about it in chat! + 1

  • ehehehe How rare it is to use chat I didn’t realize. My bad

  • 1

    I needed to see if there’s anything about differences in empty, is_null, isset, because if not, it would be a good idea to open a well-designed question. It would make a nice piece of documentation in the OS.

  • I agree, go ahead :)

4

In addition to the solutions presented by @Rbz, you can create a method as suggested below to verify 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));

Exit:

bool(false)
bool(true)

As recommended by the staff, re-evaluate the form submission, use the client validations with the HMTL5 resources etc. You can also use some library to validate on the server side if the application becomes more complex.

Test the online code on: https://ideone.com/F1K8b4

Browser other questions tagged

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