empty function not working while checking form field array - php

I have an array of html textbox element with name say date_field[]. There could be multiple fields in the form. After submission of the form to check whether at least one of the textbox is not empty, I used -
<?php
if(empty($_POST["date_field"])){
echo "Is empty";
}else{
echo "is not empty";
}
?>
It echoed is not empty no matter whether I fill or I didn't fill this date_field.
P.S. If I printed the form value using print_r
If I didn't put value
[followup_date] => Array
(
[0] =>
)
if I put value
[followup_date] => Array
(
[0] => 2012-12--14
)
Any help will be highly appreciated

Your "empty" array contains an empty string:
array(0 => '')
That's not an empty array. The only "empty" array is array().
You may want to run it through array_filter, which removes all elements evaluating to false (which also includes "0", be careful).

The array is not empty since it will contain one element per non-disabled form field (even when those fields are empty).
You could use the array_filter function as mentioned by #deceze, but remember that this would also remove some elements which a human wouldn't consider to be empty.
Therefore I'd rather run through the array myself and check if all elements are empty in the matter that you want. For example:
function all_is_empty(array $subject)
{
foreach($subject as $value)
if(str_len($value) > 0)
return false;
return true;
}
Usage:
if(all_is_empty($_POST["date_field"]))
{
echo "Is empty";
}
else
{
echo "is not empty";
}
If this was me, I'd probably also combine this with checking that all the fields were valid. So if you know all the fields in that array should be dates, check that they actually are :)

Related

in_array() not working properly using $_POST

I'm trying to let the user select multiple countries and then check if the countries he selected are in the array of allowed countries using PHP
I used javascript for multiple options , this is why it is not found in the tags. Otherwise for testing you can put some custom options between the tags. (country codes in this case)
HTML:
<form method="POST" action="">
<select name="countries[]" class="country" multiple></select>
<button type="submit">Submit</button>
</form>
PHP:
<?php
if(isset($_POST['countrylist'])) {
$arr = array("FR","GF","PF","TF","GE","DE","GI","GR","GL","HK","IS","IN","ID","IE","IL","IT","JP","JO","KZ","KR","LV","LB","LI","LT","LU","MK","MX","MD","MC","MN","MS","MA","NP","NL","NZ","NO","PK"); //These are allowed country codes which are sent by the user the same way as above using POST request. The sent array looks fine as you can see in the var_dump result below.
$array2 = (array) $_POST['countries'];
$array2= array_filter($array2);
if(!in_array($array2, $arr)) {
echo var_dump($array2);
}
}
?>
The in_array() function doesn't seem to work , my var_dump result looks something like this:
array(1) { [0]=> string(2) "FR" } //If I selected France country for example.
$arr is an array of strings. $array2 is an array of strings (just one string in this case).
You are using $array2 as your needle, so you are asking "Does this array appear in this set of strings", which is doesn't, because the array isn't a string.
You would need to do something more like in_array($array2[0], $arr).
That, of course, misses the point since you want to accept multiple values, but it is a place to start.
You need to loop over $array2 and test each value in turn until you get to the end or hit a failure state. You might also look at using array_filter again, this time passing a callback.
in_array() works just fine but you call with wrong arguments. The first argument that it expects is a value to search in the second argument (that must be an array).
Since you have an array of values that you want to search you can either try to search each value at a time using in_array() or you can use array_intersect() to find the values that are present in both arrays.
Your choice will be influenced by the way you decide to handle the unexpected values in the input.
Example using in_array():
$knownValues = ['FR', 'GF', 'PF', 'TF'];
if (! is_array($_POST['countries'])) {
// The input does not look valid; there is nothing to process
// Handle this in the most appropriate way for your application and stop here
// return/exit/throw/whatever
}
$valid = [];
foreach ($_POST['countries'] as $countryId) {
if (! in_array($countryId, $knownValues)) {
// $countryId is not a valid/known country code
// Do something with it (report it, ignore it etc.)
continue;
}
$valid[] = $countryId;
}
// Here $valid contains the input values that are present in $knownValues
Example using array_intersect():
$knownValues = ['FR', 'GF', 'PF', 'TF'];
if (! is_array($_POST['countries'])) {
// The input does not look valid; there is nothing to process
// Handle this in the most appropriate way for your application and stop here
// return/exit/throw/whatever
}
$valid = array_intersect($_POST['countries'], $knownValues);
$invalid = array_diff($_POST['countries'], $knownValues);
// The known/valid and unknown/invalid values have been separated
// Do whatever you want with them.

How to check if a PHP POST array has any value set?

I need to check if any item in an array, that is part of a $_POST array, has a value. The values in the empty array are set, so the above example will not produce the desired results. (This array is a subset of the full $_POST array).
(
[columns] =>
[coached_textbox] => 1
[item] => Array
(
[first] => Array
(
[coach_menu_value] => one
[coach_menu_name] => Menu One
)
[second] => Array
(
[coach_menu_value] =>
[coach_menu_name] =>
)
(
Is there a simple way to test if either array item has a value? I could test each item in the array for value, but that seems inelegant.
This example provided in earlier post gives a fine example on how to test a code initialized array() for values.
if ($signup_errors) {
// there was an error
} else {
// there wasn't
}
However, it doesn't work on an array set within a $_POST array.
Use a recursive function like below to traverse the array. The function will return true if the array contains at least one non-null value or non-empty string.
function traverseArray($arr){
$flag = false;
foreach($arr as $value){
if(is_array($value)){
$flag = traverseArray($value);
if($flag) return true;
}else{
if(isset($value) && $value != '') return true;
}
}
return $flag;
}
And this is how you should call this function,
(Suppose $array is your original array)
$isNonEmptyArray = traverseArray($array);
if($isNonEmptyArray){
// At least one element in the array is either
// non-null value or non-empty string
}else{
// Array is completely empty
}
Here's a live demo: https://eval.in/847211
You can filter out the empty values and check for empty():
if (empty(array_filter($_POST['item']['second']))) {
// It is empty
} else {
// It is NOT empty
}
Or even just check for falsey value:
if (!array_filter($_POST['item']['second'])) {
// It is empty
} else {
// It is NOT empty
}

Condition failing even if the array values are empty

I have a piece of code where the condition fails even when the array is empty.
This is the code:
echo "<pre>";
print_r($_FILES['jform']['name']['gallery']);
which outputs
Array
(
[0] =>
)
This is the condition:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile))
{
//do something
}
It should fail, but the program enters the if block. Why?
As you can see from the print_r() the array is NOT empty - it has one element, which on the other side looks like white space or empty.
Update
I would recommend reading POST method uploads, where you'll learn that name is the original name of the file and tmp_name is a random name of the temporary file, that has been just uploaded.
According to my experience you should check the Error Messages.
The check you're interested is:
foreach ( array_keys( $_FILES['jform']['gallery'] ) AS $key ) {
if ( UPLOAD_ERR_OK == $_FILES['jform']['gallery']['error'][$key] ) {
// do the stuff with the uploaded file in $_FILES['jform']['gallery']['tmp_name'][$key]
}
}
Keep an eye on the names of the arrays where gallery is before name.
As you can see your array is not empty it has a blank element.
The work around is array_filter which will eliminate blank data
$array = array(0=>'');
$array1 = array_filter($array);
print_r($array1);
if(!empty($array1)){
echo "has elememt";
}else{
echo "empty";
}
This is what u need
UPDATE
What if the value contains multiple spaces, yes this could be handled using a call back function
$array1 = array_filter($array,"call_back_function");
function call_back_function($val){
return trim($val);
}
In your case print_r() told you that galfile == array('') // 1 element is in the array
According to the documentaion only array() // 0 elements is considered empty. So the if statement is executed correctly.
In your case you should write:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile) && !empty($galfile[0]) )
{
//do something
}
When you working with arrays, before checking for empty you can sanitize your array using array_filter or the similar functions:
$galfile = array_filter($_FILES['jform']['name']['gallery']);
if(!empty($galfile))
{
//do something
}
But when you use global array _FILES, more correctly is checks for error:
if($_FILES['jform']['error']['gallery'] == 0)
{
//do something
}
P.S. If you want to filtering all array elements, you can use filter_var_array

Adding a key to a foreach created array not adding all values

foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'] = $door_check;
}
I have this little section of code that checks how many boxes were checked and then creates an array of the check box values.
The thing is, when I add that 'door' key, the array only adds one value no matter how many checkboxes were checked. When I just leave it empty, it adds all of them like [0], [1], [2] etc
Why is this?,
Your foreach() loops overwrites old variable each time. You need to make your session variable an array, for example
foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'][] = $door_check;
}
edit: Don't forget to validate that data when you save it for later use.
Try something like this:
foreach($_POST['door_check'] as $door_check) {
$_SESSION['front_door']['door'][] = $door_check;
}
or maybe even:
$_SESSION['front_door']['door'] = $_POST['door_check'];

Compare PHP arrays

I know there are a lot of these, but I'm looking for something slightly different.
A straight diff won't work for me.
I have a list (array) of allowed tags i.e. ["engine","chassis","brakes","suspension"]
Which I want to check with the list the user has entered. Diff won't work, because the user may not enter all the options i.e. ["engine"] but I still want this to pass. What I want to happen is fail if they put something like "banana" in the list.
You can use array_intersect(), and check the size of the resulting array with the size of the input array. If the result is smaller, then the input contains one or more items not in the 'allowed' array. If its size is equal, all items in it are in the user's input, so you can use the array do do whatever you want.
Use array_diff();
$allowed=array("engine","chassis","brakes","suspension");
$user=array("engine","brakes","banana");
$unallowed=array_diff($user, $allowed);
print_r($unallowed);
This will return banana, as it is in $user, but not in $allowed.
array_diff(): http://nl.php.net/array_diff
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
if ( array_diff( $input, $allowed ) ) {
// error
}
$allowed_tags = array("engine","chassis","brakes","suspension");
$user_iput = array("engine", "suspension", "banana");
foreach($user_input as $ui) {
if(!in_array($ui, $allowed_tags)) {
//user entered an invalid tag
}
}

Categories