php - what does ($variable) return?

973

just doing some validation and wanted to learn really what this meant instead of it just working.

Lets say i have:

$email = $_POST['email'];
if(!$email) { 
echo 'email empty'
}

Whats is just having the variable and no check for it = something mean?

I thought

$variable

by its self meant that it returned that variable as true.

So i am also using if

!$variable

is means false.

Just wanted to clear up the actual meaning behind just using the variable itself.

Is it also bad practice to compare the variable for being empty?

So is it better to use

$email == ''

Than

!$email

Sorry if its a small question without a real answer to be solved, just like to 100% understand how what i am coding actually works.

770

Answer

Solution:

PHP evaluates if$email is "truthy" using the rules defined at http://www.php.net/manual/en/language.types.boolean.php.

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

PS$email= '' will assign'' to$email.

331

Answer

Solution:

$email = '' will empty the variable. You can use== or=== instead.

In this case, it's better to use PHP'sisset() function (documentation). The function is testing whether a variable is set and notNULL.

133

Answer

Solution:

When you doif(<expression>), it evaluates<expression>, then converts it to a boolean.

In the docs, it says:

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

So, when you doif(!$email), it converts$email to a boolean following the above rules, then inverts that boolean.

People are also looking for solutions to the problem: php - How to reject a file upload in a web server before it is uploaded

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.