Scroll through an Array and check if any element is empty

Asked

Viewed 29,077 times

4

Is there a native PHP function to traverse a array and check if any element of this array is empty null?

Observe the code below:

if(isset($_POST['btnCriaModelo'])){

  $instArray  = $_POST['idInstrucao'];
  $orderArray = $_POST['ordem'];

  for ($i=1; $i < count($instArray) ; $i++) { 

     /*
       Aqui é onde pensei em fazer essa verificação mas não consigo criar uma lógica.
       A variável auxilar $i começa com o valor 1 por que naturalmente no meu código
       o primeiro elemento destes vetores acima são vazios, porém todos os outros elementos
       não podem se quer um está vazios 
     */

  }               

}

The reason why I need to do this check is to do a validation with PHP. If there is an empty vector element I do not rotate the insertion loop in my database.

10 answers

7

There are many ways to check if the element is empty. For example, following this scheme:

if (elemento é vazio) {
    faça qualquer coisa
}

You must define what "empty" means: null? 0 is empty? the boolean false is empty? an empty string ("") is empty? and a space " "?

Then there are a multitude of methods of building your conditional, each one will return true or false according to the content of the variable, some consider 0 empty and others not...

Here are some examples.

Function is_null()

Will return true only if the element does not exist or is equal to null.

if (is_null($elemento)) {
    // O elemento é vazio, faça qualquer coisa
}

Function Empty()

Will return true if the element does not exist, is equal to null, if it is equal to false, if it is equal to "", if it is equal to 0, if it is equal to 0.0, if it is equal to "0" or whether it is equal to array() (empty array).

if (empty($elemento)) {
    // O elemento é vazio, faça qualquer coisa
}

Isset function()

Will return false only if the element does not exist, or is equal to null.

if (!isset($elemento)) {
    // O elemento é vazio, faça qualquer coisa
}

Logical operators

You can also use logical operators to prove equality with one or more of the possible meanings of "empty". For example:

if ($elemento === 0) {
    // O elemento é exatamente o número inteiro "zero", faça qualquer coisa
}

if ($elemento === "") {
    // O elemento é exatamente um string vazio, faça qualquer coisa
}

7


4

You can use a array_filter php native.

Take an example:

<?php

$entry = array(
    0 => 'foo',
    1 => false,
    2 => -1,
    3 => null,
    4 => ''
);

print_r(array_filter($entry));

This is the way out:

Array
(
  [0] => foo
  [2] => -1
}

That is, the array_filter ignored what has values false, null and Empty.

In this case you can iterate on the valid results.

3

In associative arrays it is best to use one foreach since the keys of your array are not numeric where a cycle for can be used as you have in your question:

So an example:

if (isset($_POST['btnCriaModelo'])) {
    $instArray = $_POST['idInstrucao'];
    $orderArray = $_POST['ordem'];

    foreach($instArray as $chave => $valor){ //se não quer a chave pode usar só ($instArray as $valor)
        if($valor != ''){  
            // fazer qualquer coisa no caso de não ser vazio
            echo 'A idInstrucao é: '.$chave.' e o seu valor é: '.$valor;
        }
    }
}

Demo

3

If you go through the entire array you can use one is_null to validate whether or not it is null and empty whether it is empty or not.

<?php
$arr = array('teste', 'teste 2', 123, '', null, false);
foreach ($arr as $value) {
    if (is_null($value)) {
        echo 'Nulo';
    } else if (empty($value)) {
        echo 'Vazio';
    } else {
        echo $value;
    }
}

Recalling that the Empty validates whether the variable is empty, as the albertedevigo said if it is 0, false or "" he returns true

2

If you just want to find the first occurrence, you can use the functions in_array or array_search.

If you want to find all occurrences if there is more than one, it is best to cross the array using foreach.

1

You can choose to sweep the array and close the loop as soon as the array finds an empty element:

$erro = false;
foreach ( $meuArray as $valor ) :
  if ( empty($valor) || $valor === null ) :
    $erro = 'Opa! Você está com campos vazios!';
    break; // Esse break encerrará o foreach!
  endif;
endforeach;

if ( !$erro ) :
  // Você pode gravar no banco!
endif;

1

You can use the function in_array of PHP as in the following example:

if(in_array(NULL, $variavel)){
   /*Tem valor NULL em uma variável*/
}

0

$posicoesVazias = array_keys($array, '', TRUE);

if(empty($posicoesVazias)){

    // Sem itens vazios

}else{

    echo "Os itens " . implode(', ', $posicoesVazias) . " estão vazios.";

}

0

In this case, it has already been mentioned earlier about the function Empty, that checks if the value is null, "", 0, array().

The function array_filter() remove any of these cited within the array passed as parameter.

In a few lines, there is a way to check if there is any empty value within an array, that is, comparing the original array with the "filtered array"

<?php

$array = array('teste', 'outro teste', array(), 0);

if($array === array_filter($array)){
   echo 'Não existem elementos vazios';
}
else{
   echo 'Existem elementos vazios';
}

Browser other questions tagged

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