简体   繁体   中英

Where does the additional 0 come from

I have been a developer for more than 5 years but this seems to be confusing and strange. I tried to use two functions having echo on each function. Then, I call those functions and echoed again. Why does this code below displays 5100 instead of 510 only? Where does the additional 0 come from?

<?php

function firstNum()
{
  echo 5;
}

function secondNum()
{
  echo 10;
}

echo firstNum() + secondNum(); //Output is 5100

Your code is echoing 5 then 10 then the sum of null plus null .

When you don't use a return php will return null from the function call.

You mean to do this: ( Demo )

function firstNum()
{
  return 5;
}

function secondNum()
{
  return 10;
}

echo firstNum() + secondNum(); //Output is 15

You can remove the echo s in the function to have a better understanding of what is returned: ( Demo )

function firstNum()
{
  //echo 5;
}

function secondNum()
{
  //echo 10;
}

var_export(firstNum());
echo "\n";
var_export(secondNum());
echo "\n";
var_export(null+null);

Output:

NULL
NULL
0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM