Traverse an Array and check if any element is empty

3

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

Look at 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 I need to do this is to do a validation with PHP. If there is any element of the empty vector I do not wrap the insertion loop in my bank.

    
asked by anonymous 31.01.2014 / 08:47

9 answers

7

The simplest solution to your problem is:

$valido = (false === array_search(false , $instArray, false));

Example: link

    
31.01.2014 / 11:53
6

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

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

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

Then there are a myriad of methods to construct your conditional, each one will return true or false depending on the contents of the variable, some consider 0 empty and others not ...

Here are some examples.

Function is_null ()

It 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
}

empty ()

Returns% with% if element does not exist, is equal to true , if it is equal to null , if equal to false , if equal to "" , if equal to 0 , if it is equal to 0.0 or if it is equal to "0" (empty array).

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

Function isset ()

Returns array() only if element does not exist, or is equal to false .

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
}
    
31.01.2014 / 10:59
3

You can use a array_filter native to php.

See an example:

<?php

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

print_r(array_filter($entry));

The output will be this:

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

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

In this case you can iterate over the valid results.

    
31.01.2014 / 14:25
2

In associative arrays it is best to use a foreach > since the keys in your array are not countable where a for loop 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

    
31.01.2014 / 10:27
2

If you go through the entire array you can use is_null to validate whether it is null or not 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;
    }
}

Remembering that the empty validates if the variable is empty, so that the albertedevigo said that if it is as 0 false or "" it returns true

    
31.01.2014 / 11:44
2

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

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

31.01.2014 / 09:03
1

You can choose to scan array and close the loop once 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;
    
31.01.2014 / 14:25
1

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

if(in_array(NULL, $variavel)){
   /*Tem valor NULL em uma variável*/
}
    
31.01.2014 / 16:18
0

In this case, the empty function, which checks to see if the value is null,

The array_filter () function removes any of these within the array passed as a parameter.

In a few lines, there is a way to check if there is any empty value inside an array, ie 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';
}
    
20.03.2014 / 16:52