Aymane Shuichi
Aymane Shuichi

Reputation: 458

How does PHP interpret Javascript's Null value?

Sol let's suppose that we send a post query to a PHP file, this query where we have ...&title=title where title is for example title=$(#title).val(); (assuming we're including Jquery) in PHP we have $title=$_POST['title']; Let's suppose then that title is null , will PHP consider null as string ? or something empty ?

Upvotes: 3

Views: 3727

Answers (4)

Sasi Varunan
Sasi Varunan

Reputation: 2864

php intercepts js null as "null" -> string, So to handle form request, i had small work around in my php code like below

function checknull($arg){
    if($arg == "null"){
      return;
    }else{
        return $arg;
    }
}
$a=array();
$b = "null";
$a['hi'] = checknull($b);
var_dump($a);

This will output as

array(1) { ["hi"]=> NULL }

//same you can test it for $_REQUEST

$var1 = checknull($_POST['title']);
var_dump($var1);

or you can use

$var1 = $_POST['title'] === 'null'? NULL : $_POST['title'];
var_dump($var1);

Upvotes: 0

mewm
mewm

Reputation: 1277

In your case, if you send a $(#title).val(); as data in an ajax request to a php script, and the input is empty, it would just be an empty string.

Upvotes: 1

ComFreek
ComFreek

Reputation: 29424

The title gets converted to a string before sending it to the server.

Converting the JS value null to a string results in a string "null". Therefore, PHP will only interpret the variable as a string.

However, I doubt that you will receive a null value from an empty input box. You will get an empty string instead.

Upvotes: 2

Amal Murali
Amal Murali

Reputation: 76646

From the PHP Manual:

The special NULL value represents a variable with no value. NULL is the only possible value of type NULL.

A variable is considered to be NULL if:

  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset().

"NULL" is not the same as NULL.

var_dump("null" == NULL);

Outputs:

bool(false)

Upvotes: 4

Related Questions