What is the PHP syntax to check "is not null" or an empty string?

PhpVariablesNullConditional Statements

Php Problem Overview


> Possible Duplicate:
> Check if a variable is empty

Simple PHP question:

I have this stement:

if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
...//IF PASSWORD IS CORRECT STUFF WILL HAPPEN HERE
}

Somewhere above this statement I use the following line in my JavaScript to set the username as a variable both in my JavaScript and in my PHP:

uservariable = <?php $user = $_POST['user']; print ("\"" . $user . "\"")?>;

What I want to do is add a condition to make sure $user is not null or an empty string (it doesn't have to be any particular value, I just don't want it to be empty. What is the proper way to do this?

I know this is a sill question but I have no experience with PHP. Please advise, Thank you!

Php Solutions


Solution 1 - Php

Null OR an empty string?

if (!empty($user)) {}

Use empty().


After realizing that $user ~= $_POST['user'] (thanks matt):

var uservariable='<?php 
    echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';

Solution 2 - Php

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

> The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionI wrestled a bear once.View Question on Stackoverflow
Solution 1 - PhpJohn GreenView Answer on Stackoverflow
Solution 2 - PhpJohn CondeView Answer on Stackoverflow