Asked  7 Months ago    Answers:  5   Viewed   35 times

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?

I want to ensure that:

  1. null is considered an empty string
  2. a white space only string is considered empty
  3. that "0" is not considered empty

This is what I've got so far:

$question = trim($_POST['question']);

if ("" === "$question") {
    // Handle error here
}

There must be a simpler way of doing this?

 Answers

28
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
    return (!isset($str) || trim($str) === '');
}
Wednesday, March 31, 2021
 
mikelovelyuk
answered 7 Months ago
27

I like if ((item.Rate ?? 0) == 0) { }

Update 1:

You could also define an extension method like:

public static bool IsNullOrValue(this double? value, double valueToCheck)
{
    return (value??valueToCheck) == valueToCheck;
}

And use it like this:

if(item.IsNullOrValue(0)){} // but you don't get much from it

Monday, June 21, 2021
 
Kevin_Kinsey
answered 4 Months ago
92

Validation is part of the domain logic. Controller should have nothing to do with this. It only has to pass the incoming request values to the proper parts of model layer.

The validation itself should happen in domain objects within the model layer. Also, in some forms you have to worry about data integrity (i.e. unique usernames in registration form). In that case the data integrity checks actually should be handled by data mappers by, essentially, passing data to SQL database, which performs the check and, if there is a violation, it triggers an exception on DB abstraction.

Update

Since your problems is dealing with authentication/authorization, you might find this post relevant.

Thursday, August 12, 2021
 
AlterPHP
answered 2 Months ago
89

In your example you are never incrementing the variable $j.

Try a foreach instead:

foreach($j=2; $j<=10; $j++) {
  //do your stuff
}

Or change it up to be a do-while http://php.net/manual/en/control-structures.do.while.php

Wednesday, August 18, 2021
 
Aran Mulholland
answered 2 Months ago
72

Use the MERGE intrinsic function:

masked = my_array * merge(1,0,my_array<=15.0)
Saturday, October 16, 2021
 
codeforester
answered 2 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :