Ramesh_Konda
Ramesh_Konda

Reputation: 111

Why php takes by default NULL as zero

 <?php
    $a = NULL;
    $a++;
   echo "a value is $a";
   ?>

It outputs: a value is 1.

<?php
$a = NULL;
echo "a values is $a";
?>

It outputs:
a value is

Am confused about this.. please explain me

Upvotes: 0

Views: 78

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31739

For -

<?php
$a = NULL;
$a++;
echo "a value is $a"; 
?>

When this operation is performed $a first converted to integer and gets the value 0 in it as it was containing NULL. So it is printing 1 as value.

For -

<?php
$a = NULL;
echo "a values is $a";
?>

No conversions are applied here as it is printed as it is. So it is printing nothing there.

Upvotes: 0

Pupil
Pupil

Reputation: 23948

It is PHP's Type Casting

http://php.net/manual/en/language.types.type-juggling.php

PHP automatically changes type of variable depending upon the operation.

Explanation:

Your code

<?php
$a = NULL; // $a is NULL
$a++;
?>

But, increment ++ is applicable only to integer values, so when you write $a++, it automatically converts $a to integer and as it is NULL, it is set to 0 and then incremented.

Upvotes: 1

Related Questions