Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Initialising strings as boolean first

I'm in the habit of initialising variables in PHP to false and then applying whatever (string, boolean, float) value to it later.

Which would you reckon is better?

$name = false;
if (condition == true) {
    $name = $something_else;
}

if ($name) {  …do something…  }

vs.

$name ='';
if (condition == true) {
    $name = $something_else;
}

if (!empty($name)) {  …do something…  }

Which would you reckon can possibly give better performance? Which method would you use?

like image 606
Anriëtte Myburgh Avatar asked Jan 11 '23 22:01

Anriëtte Myburgh


2 Answers

At first glance - your $condition==true is pointless since $condition is well enough.

Second - if you're not sure what type will be variable, but you want to initialize it (that is - indeed - a good habit), use null - since false points to certain data type - bool data type, while it's not correct and person who reads your code may be confused.

like image 188
Alma Do Avatar answered Jan 16 '23 22:01

Alma Do


Both values '' as false have meaning.

I would suggest using null as the default value. Since that actually does not (and should not) 'mean' anything.

This will also allow you to test is_null($var) to make sure something actually set a value to your variable.

like image 34
Damien Overeem Avatar answered Jan 16 '23 22:01

Damien Overeem