Jump to content

How to check if value in array is empty


t_machine

Recommended Posts

Hi, I am wondering if anyone could help with this problem.

I have an array that checks values in post and I would like to check if any of the post field is empty so I can let the user know that they can't post an empty field.

I have the following
$mycheck = array();
$mycheck['one'] = $var1;
$mycheck['two'] = $var2;
$mycheck['three'] = $var3;

Let's say $var3 is blank, how can I check the array and print that one of the field is empty?

Thanks :)
Link to comment
https://forums.phpfreaks.com/topic/27484-how-to-check-if-value-in-array-is-empty/
Share on other sites

Without doing loops, you can use array_diff() inside another array_diff()...

[code]<?php

// array to check

$check = array ( 'first_name' => 'Sonia', 'last_name' => '', 'age' => '', 'email' => '[email protected]' );

// returns all the elements that are empty, using (trim) before testing

$empty = array_diff ( $check, array_diff ( array_map ( 'trim', $check ), array ( '' ) ) );

print_r ( $empty );

?>[/code]


If you are checking posted values from a form, this is a working example on how you can do that (remember to make the vars safe though)

Example:
[code]

<?php

$empty_arr = array();

foreach($_POST as $fieldname => $fieldvalue)
{
  if(empty($fieldvalue))
  {
    $empty_arr[] = $fieldname." was left empty";
  }
  ${$fieldname} = $_POST[$fieldname]; // <-- remember to make them safe using strip_tags, addslashes etc
}

if(!empty($empty_arr))
{
  echo "<ul><li>";
  echo implode($empty_arr, '</li><li>');
  echo "</li><ul>";
}
else
{
  // no empty fields, prosess posted values already defined as $fielnames
}

?>

[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.