Check if an array has empty values

Asked

Viewed 54 times

0

I want this foreach to check if there are empty values inside the array, and if there is, display the "error" message. How can I do it right?

if (isset($_POST['start'])) {
foreach ($_POST['start'] as $key => $value) {
echo '<br>';
    $start2 = mysql_real_escape_string($value);  // data da saida
    $cod = mysql_real_escape_string($_POST['cod'][$key]); 
    $id_cotacao = mysql_real_escape_string($_POST['id_cotacao'][$key]);// id         
}}

For example:

 linha 1 ==> 2017-12-01 | 10 | 21
 linha 2 ==> 2017-12-01 |    | 21
 linha 3 ==> 2017-12-01 | 10 | 21

If it finds an empty variable, it shows the error message.

  • You can use the function empty

1 answer

1


It wasn’t very clear from the example you gave, but you can make a comparison by counting the received array with the 'filtered' array without the empty indices, just use array_filter as in the example below. See running on ideone.

$post = [ 'a' => 'valor A' , 'b' => '' , 'c' => 'valor C' ];


if( count( $post ) !== count( array_filter( $post ) ) )
{
    echo 'erro!';
}
else
{
    echo 'ok!';
}

count( $post ) // output 3
count( array_filter( $post ) ) // output 2

Browser other questions tagged

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