isset and != ''

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jonemo
Forum Commoner
Posts: 28
Joined: Wed Feb 09, 2005 1:32 pm
Location: london, uk

isset and != ''

Post by jonemo »

is there any difference between the following two code snippets?

Code: Select all

if (isset($t))

Code: Select all

if ($t != '')
i.e. can it happen that the two conditions have different results with the same $t?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the second can, and will produce an "undefined variable: t" error/warning/notice. The first will not.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

you're better off using

empty() and isset()


feyd | ;)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

with array keys there are some differences between != '', isset, array_key_existst and empty.
jonemo
Forum Commoner
Posts: 28
Joined: Wed Feb 09, 2005 1:32 pm
Location: london, uk

Post by jonemo »

so what is the difference between between empty() and isset() then? and is it only for arrays or is a variable that gets the value NULL still set? as the main use for stuff like that is to check $_REQUEST[] stuff, it deals with arrays...
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

how about reading the manual and experimenting yourself?

Code: Select all

<?php
echo "<br>nothing set<br>";

if (isset($val))
&#123;
    echo "isset";
&#125;
else
&#123;
    echo "not isset";
&#125;
echo "<br>";
if (empty($val))
&#123;
    echo "empty";
&#125;
else
&#123;
    echo "not empty";
&#125;

echo "<br> assign test<br>";

$val = "test";
if (isset($val))
&#123;
    echo "isset";
&#125;
else
&#123;
    echo "not isset";
&#125;
echo "<br>";
if (empty($val))
&#123;
    echo "empty";
&#125;
else
&#123;
    echo "not empty";
&#125;

echo "<br>assign null<br>";

$val = null;
if (isset($val))
&#123;
    echo "isset";
&#125;
else
&#123;
    echo "not isset";
&#125;
echo "<br>";
if (empty($val))
&#123;
    echo "empty";
&#125;
else
&#123;
    echo "not empty";
&#125;
echo "<br>";
?>

feyd | naughty timvw! ;)
jonemo
Forum Commoner
Posts: 28
Joined: Wed Feb 09, 2005 1:32 pm
Location: london, uk

Post by jonemo »

why not ask the clever people in the forum before writing test scripts?

thanks for the code, but i actually just coded the same (before i saw your answer) :)
Post Reply