Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Introducing Functions PHP Function Default Arguments

Why does if($title) work instead of using a != in the following code?

The lesson's code example is:

<?php
function get_info($name, $title = Null){

  if($title){
    echo "$name has arrived. They are with us as a $title.";
  } else {
    echo "$name has arrived. They have no title.";
  }
}

get_info("Mike");
?>

What I'm not understanding is why if($title) works vs. needing to phrase it as:

if($title != null) 

Thanks for your help!

2 Answers

andren
andren
28,558 Points

This is because PHP (and some other languages) will always try to convert things that do not return a Boolean value (true or false) into a Boolean value if it is used in a place that only accepts Booleans.

It does so using some rules built into the language. If the value is null, the number 0 or an empty string then it will be treated as false. There are a couple more values that are treated as false but they are all along those same lines, values that could be seen as representing something empty. If the value is not on the list of values to be treated as false then it is treated as true.

So if $title is null or an empty string it will be treated as false and as such the else statement will run, if it has some contents then it will be treated as true and the if statement will run.

You can Google "PHP Truthy" if you want more details about this process, like the full list of values that are treated as false for example.

Alexandre Babeanu
Alexandre Babeanu
10,947 Points

It is because of php's ability to juggle types.

I used to do java and in java you have to specify the type of a variable so you'll declare your variable like this :

int a = 2;

And so you cannot put anything else in a but Integers.

In php though, php will automatically change the type. So basically when writing if($string) the if statement is waiting for a boolean, php will automatically change $string to a boolean.

to do so PHP looks into $string : if it contains a string that's not empty it will change $variable into the boolean TRUE, if the string is empty it will change $variable to boolean FALSE.

That is why if($variable) actually works...

hope that is clear!