Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 451
I wrestled a bear once. Avatar asked Jun 26 '12 17:06

I wrestled a bear once.


People also ask

How check string is empty or NULL in PHP?

You can use isset() , empty() , or is_null() to check if either one or all of those conditions are true or false.

IS NOT NULL check in PHP?

The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.

What is NULL and empty in PHP?

A variable is NULL if it has no value, and points to nowhere in memory. empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL . The following things are considered to be empty: "" (an empty string) 0 (0 as an integer)

What is not empty in PHP?

The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.


2 Answers

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'; ?>'; 
like image 173
John Green Avatar answered Oct 01 '22 23:10

John Green


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)   
like image 31
John Conde Avatar answered Oct 01 '22 23:10

John Conde