You are on page 1of 32

26/4/2017 PHP:issetManual

Downloads
Documentation
GetInvolved
Help

Search

GettingStarted
Introduction
Asimpletutorial
LanguageReference
Basicsyntax
Types
Variables
Constants
Expressions
Operators
ControlStructures
Functions
ClassesandObjects
Namespaces
Errors
Exceptions
Generators
ReferencesExplained
PredefinedVariables
PredefinedExceptions
PredefinedInterfacesandClasses
Contextoptionsandparameters
SupportedProtocolsandWrappers

Security
Introduction
Generalconsiderations
InstalledasCGIbinary
InstalledasanApachemodule
SessionSecurity
FilesystemSecurity
DatabaseSecurity
ErrorReporting
UsingRegisterGlobals
UserSubmittedData
MagicQuotes
HidingPHP
KeepingCurrent
Features
HTTPauthenticationwithPHP
Cookies
Sessions
DealingwithXForms
http://php.net/manual/es/function.isset.php 1/32
26/4/2017 PHP:issetManual

Handlingfileuploads
Usingremotefiles
Connectionhandling
PersistentDatabaseConnections
SafeMode
Commandlineusage
GarbageCollection
DTraceDynamicTracing

FunctionReference
AffectingPHP'sBehaviour
AudioFormatsManipulation
AuthenticationServices
CommandLineSpecificExtensions
CompressionandArchiveExtensions
CreditCardProcessing
CryptographyExtensions
DatabaseExtensions
DateandTimeRelatedExtensions
FileSystemRelatedExtensions
HumanLanguageandCharacterEncodingSupport
ImageProcessingandGeneration
MailRelatedExtensions
MathematicalExtensions
NonTextMIMEOutput
ProcessControlExtensions
OtherBasicExtensions
OtherServices
SearchEngineExtensions
ServerSpecificExtensions
SessionExtensions
TextProcessing
VariableandTypeRelatedExtensions
WebServices
WindowsOnlyExtensions
XMLManipulation
GUIExtensions

KeyboardShortcuts
?
Thishelp
j
Nextmenuitem
k
Previousmenuitem
gp
Previousmanpage
gn
Nextmanpage
G
Scrolltobottom
gg
Scrolltotop
gh
http://php.net/manual/es/function.isset.php 2/32
26/4/2017 PHP:issetManual

Gotohomepage
gs
Gotosearch
(currentpage)
/
Focussearchbox

print_r
is_string

ManualdePHP
Referenciadefunciones
Extensionesrelacionadasconvariableytipo
Manejodevariables
Funcionesdemanejodevariables

Changelanguage: Spanish
EditReportaBug

isset
(PHP4,PHP5,PHP7)

issetDeterminasiunavariableestdefinidaynoesNULL

Descripcin

boolisset(mixed$var[,mixed$...])

DeterminasiunavariableestdefinidaynoesNULL.

Siunavariablehasidoremovidaconunset(),estayanoestardefinida.isset()devolverFALSEsipruebauna
variablequehasidodefinidacomoNULL.TambintengaencuentaqueunbyteNULL("\0")noesequivalenteala
constanteNULLdePHP.

Sisonpasadosvariosparmetros,entoncesisset()devolverTRUEnicamentesitodoslosparmetrosestn
definidos.Laevaluacinserealizadeizquierdaaderechaysedetienetanprontocomoseencuentreuna
variablenodefinida.

Parmetros
var

Lavariableaserevaluada.

...

Otravariable...

Valoresdevueltos

DevuelveTRUEsivarexisteytieneunvalordistintodeNULL,FALSEdelocontrario.
http://php.net/manual/es/function.isset.php 3/32
26/4/2017 PHP:issetManual

Historialdecambios

Versin Descripcin

5.4.0 ComprobacindeindicesnonumricosdestringsahoraretornaFALSE.

Ejemplos

Ejemplo#1Ejemplosisset()

<?php

$var='';

//EstoevaluaraTRUEasqueeltextoseimprimir.
if(isset($var)){
echo"Estavariableestdefinida,asqueseimprimir";
}

//Enlossiguientesejemplousaremosvar_dumpparaimprimir
//elvalordevueltoporisset().

$a="prueba";
$b="otraprueba";

var_dump(isset($a));//TRUE
var_dump(isset($a,$b));//TRUE

unset($a);

var_dump(isset($a));//FALSE
var_dump(isset($a,$b));//FALSE

$foo=NULL;
var_dump(isset($foo));//FALSE

?>

Tambintrabajaconelementosenmatrices:

<?php

$a=array('test'=>1,'hello'=>NULL,'pie'=>array('a'=>'apple'));

var_dump(isset($a['test']));//TRUE
var_dump(isset($a['foo']));//FALSE
var_dump(isset($a['hello']));//FALSE

//Laclave'helo'esigualaNULLasquenoseconsideradefinida
//SideseacomprobarlosvaloresNULLclave,intente:
var_dump(array_key_exists('hello',$a));//TRUE

http://php.net/manual/es/function.isset.php 4/32
26/4/2017 PHP:issetManual

//Comprobandovaloresdearraysconmsprofunidad
var_dump(isset($a['pie']['a']));//TRUE
var_dump(isset($a['pie']['b']));//FALSE
var_dump(isset($a['cake']['a']['b']));//FALSE

?>

Notas
Advertencia

isset()slotrabajaconvariables,yaquepasarcualquierotracosadarcomoresultadounerrordeintrprete.
Paracomprobarsisehandefinidoconstantesuselafuncindefined().

Nota:Puestoqueestoesunaconstruccindellenguajeynounafuncin,nopuedeserllamada
usandofuncionesvariables.

Nota:

Cuandoseutilizaisset()sobrelaspropiedadesdeobjetosinaccesibles,elmtodosobrecargado
__isset()serllamado,sisedeclara.

Ejemplo#2isset()enindicesdeString

PHP5.4cambiaahoraelcomportamiendodeisset()cuandosonpasadosindicesdestring.

<?php
$expected_array_got_string='somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0Mostel']));
?>

SalidadelejemploanteriorenPHP5.3:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

SalidadelejemploanteriorenPHP5.4:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

Vertambin

http://php.net/manual/es/function.isset.php 5/32
26/4/2017 PHP:issetManual

empty()Determinasiunavariableestvaca
__isset()
unset()Destruyeunavariableespecificada
defined()Compruebasiexisteunaconstanteconnombredada
lastablasdecomparacindetipos
array_key_exists()Verificasielndiceoclavedadaexisteenelarray
is_null()CompruebasiunavariableesNULL
eloperador@decontroldeerrores

addanote

UserContributedNotes52notes
up
down
3
p_ignorethis_lbowersatgmaildotcom
6monthsago
I,too,wasdismayedtofindthatisset($foo)returnsfalseif($foo==null).Here'san(awkward)
wayaroundit.

unset($foo);
if(compact('foo')!=array()){
do_your_thing();
}

Ofcourse,thatisverynonintuitive,long,hardtounderstand,andkludgy.Bettertodesignyour
codesoyoudon'tdependonthedifferencebetweenanunsetvariableandavariablewiththevalue
null.But"better"onlybecausePHPhasmadethisweirddevelopmentchoice.

InmythinkingthiswasamistakeinthedevelopmentofPHP.Thename("isset")shoulddescribethe
functionandnothavethedesciptionbe"issetANDisnotnull".Ifitwasdoneproperlya
programmercouldveryeasilydo(isset($var)||is_null($var))iftheywantedtocheckforthis!

Avariablesettonullisadifferentstatethanavariablenotsetthereshouldbesomeeasyway
todifferentiate.Justmy(pointless)$0.02.
up
down
49
beucatbeucdotnet
10yearsago
"empty()istheoppositeof(boolean)var,exceptthatnowarningisgeneratedwhenthevariableis
notset."

Soessentially
<?php
if(isset($var)&&$var)
?>
isthesameas
<?php
if(!empty($var))
?>
doesn'tit?:)

http://php.net/manual/es/function.isset.php 6/32
26/4/2017 PHP:issetManual

!empty()mimicsthechk()functionpostedbefore.
up
down
45
yaogzhanatgmaildotcom
12yearsago
inPHP5,ifyouhave

<?PHP
classFoo
{
protected$data=array('bar'=>null);

function__get($p)
{
if(isset($this>data[$p]))return$this>data[$p];
}
}
?>

and
<?PHP
$foo=newFoo;
echoisset($foo>bar);
?>
willalwaysecho'false'.becausetheisset()acceptsVARIABLESasitparameters,butinthiscase,
$foo>barisNOTaVARIABLE.itisaVALUEreturnedfromthe__get()methodoftheclassFoo.thus
theisset($foo>bar)expreesionwillalwaysequal'false'.
up
down
28
DanielKlein
4yearsago
Howtotestforavariableactuallyexisting,includingbeingsettonull.Thiswillpreventerrors
whenpassingtofunctions.

<?php
//false
var_export(
array_key_exists('myvar',get_defined_vars())
);

$myvar;
//false
var_export(
array_key_exists('myvar',get_defined_vars())
);

$myvar=null;
//true
var_export(
array_key_exists('myvar',get_defined_vars())
);
http://php.net/manual/es/function.isset.php 7/32
26/4/2017 PHP:issetManual

unset($myvar);
//false
var_export(
array_key_exists('myvar',get_defined_vars())
);

if(array_key_exists('myvar',get_defined_vars())){
myfunction($myvar);
}
?>

Note:youcan'tturnthisintoafunction(e.g.is_defined($myvar))becauseget_defined_vars()only
getsthevariablesinthecurrentscopeandenteringafunctionchangesthescope.
up
down
23
muratyamanatgmaildotcom
9yearsago
Toorganizesomeofthefrequentlyusedfunctions..

<?php

/**
*Returnsfieldofvariable(arr[key]orobj>prop),otherwisethethirdparameter
*@paramarray/object$arr_or_obj
*@paramstring$key_or_prop
*@parammixed$else
*/
functionnz($arr_or_obj,$key_or_prop,$else){
$result=$else;
if(isset($arr_or_obj)){
if(is_array($arr_or_obj){
if(isset($arr_or_obj[$key_or_prop]))
$result=$arr_or_obj[$key_or_prop];
}elseif(is_object($arr_or_object))
if(isset($arr_or_obj>$key_or_prop))
$result=$arr_or_obj>$key_or_prop;
}
}
return$result;
}

/**
*Returnsintegervalueusingnz()
*/
functionnz_int($arr_or_obj,$key_or_prop,$else){
returnintval(nz($arr_or_obj,$key_or_prop,$else));
}

$my_id=nz_int($_REQUEST,'id',0);
if($my_id>0){
//why?

http://php.net/manual/es/function.isset.php 8/32
26/4/2017 PHP:issetManual

}
?>
up
down
21
Anonymous
10yearsago
ItriedtheexamplepostedpreviouslybySlawek:

$foo='alittlestring';
echoisset($foo)?'yes':'no',isset($foo['aaaa'])?'yes':'no';

Hegotyesyes,buthedidn'tsaywhatversionofPHPhewasusing.

ItriedthisonPHP5.0.5andgot:yesno

ButonPHP4.3.5Igot:yesyes

Apparently,PHP4convertsthethestring'aaaa'tozeroandthenreturnsthestringcharacteratthat
positionwithinthestring$foo,when$fooisnotanarray.Thatmeansyoucan'tassumeyouare
dealingwithanarray,evenifyouusedanexpressionsuchasisset($foo['aaaa']['bbb']['cc']['d']),
becauseitwillreturntruealsoifanypartisastring.

PHP5doesnotdothis.If$fooisastring,theindexmustactuallybenumeric(e.g.$foo[0])forit
toreturntheindexedcharacter.
up
down
18
SlawekPetrykowski
11yearsago
<?php
$foo='alittlestring';
echoisset($foo)?'yes':'no',isset($foo['aaaa'])?'yes':'no';
>

resultswithunexpectedvalues:
yesyes

Well,itisnecessarytochecktypeof$foofirst!
up
down
15
francoisvespa
6yearsago
Nowthisishowtoachievethesameeffect(ie,havingisset()returningtrueevenifvariablehas
beensettonull)forobjectsandarrays

<?php

//array

$array=array('foo'=>null);

returnisset($array['foo'])||array_key_exists('foo',$array)
http://php.net/manual/es/function.isset.php 9/32
26/4/2017 PHP:issetManual

?true:false;//returntrue

returnisset($array['inexistent'])||array_key_exists('inexistent',$array)
?true:false;//returnfalse

//staticclass

classbar

{
static$foo=null;
}

returnisset(bar::$foo)||array_key_exists('foo',get_class_vars('bar'))
?true:false;//returntrue

returnisset(bar::$inexistent)||array_key_exists('inexistent',get_class_vars('bar'))
?true:false;//returnfalse

//object

classbar
{
public$foo=null;
}

$bar=newbar();

returnisset($bar>foo)||array_key_exists('foo',get_object_vars($bar))
?true:false;//returntrue

returnisset($bar>inexistent)||array_key_exists('inexistent',get_object_vars($bar))
?true:false;//returntrue

//stdClass

$bar=newstdClass;
$bar>foo=null;

returnisset($bar>foo)||array_key_exists('foo',get_object_vars($bar))
?true:false;//returntrue

returnisset($bar>inexistent)||array_key_exists('inexistent',get_object_vars($bar))
?true:false;//returntrue

?>
up
down
16
AndrewPenry
11yearsago
Thefollowingisanexampleofhowtotestifavariableisset,whetherornotitisNULL.Itmakes
useofthefactthatanunsetvariablewillthrowanE_NOTICEerror,butoneinitializedasNULLwill
not.
http://php.net/manual/es/function.isset.php 10/32
26/4/2017 PHP:issetManual

<?php

functionvar_exists($var){
if(empty($GLOBALS['var_exists_err'])){
returntrue;
}else{
unset($GLOBALS['var_exists_err']);
returnfalse;
}
}

functionvar_existsHandler($errno,$errstr,$errfile,$errline){
$GLOBALS['var_exists_err']=true;
}

$l=NULL;
set_error_handler("var_existsHandler",E_NOTICE);
echo(var_exists($l))?"True":"False";
echo(var_exists($k))?"True":"False";
restore_error_handler();

?>

Outputs:
TrueFalse

Theproblemis,theset_error_handlerandrestore_error_handlercallscannotbeinsidethefunction,
whichmeansyouneed2extralinesofcodeeverytimeyouaretesting.AndifyouhaveanyE_NOTICE
errorscausedbyothercodebetweentheset_error_handlerandrestore_error_handlertheywillnotbe
dealtwithproperly.Onesolution:

<?php

functionvar_exists($var){
if(empty($GLOBALS['var_exists_err'])){
returntrue;
}else{
unset($GLOBALS['var_exists_err']);
returnfalse;
}
}

functionvar_existsHandler($errno,$errstr,$errfile,$errline){
$filearr=file($errfile);
if(strpos($filearr[$errline1],'var_exists')!==false){
$GLOBALS['var_exists_err']=true;
returntrue;
}else{
returnfalse;
}
}

$l=NULL;
http://php.net/manual/es/function.isset.php 11/32
26/4/2017 PHP:issetManual

set_error_handler("var_existsHandler",E_NOTICE);
echo(var_exists($l))?"True":"False";
echo(var_exists($k))?"True":"False";
is_null($j);
restore_error_handler();

?>

Outputs:
TrueFalse
Notice:Undefinedvariable:jinfilename.phponline26

Thiswillmakethehandleronlyhandlevar_exists,butitaddsalotofoverhead.Everytimean
E_NOTICEerrorhappens,thefileitoriginatedfromwillbeloadedintoanarray.
up
down
14
mandos78ATmailfromgoogle
8yearsago
Carefulwiththisfunction"ifsetfor"bysoapergem,passingbyreferencemeansthatif,likethe
example$_GET['id'],theargumentisanarrayindex,itwillbecreatedintheoriginalarray(witha
nullvalue),thuscausingposibletroublewiththefollowingcode.AtleastinPHP5.

Forexample:

<?php
$a=array();
print_r($a);
ifsetor($a["unsetindex"],'default');
print_r($a);
?>

willprint

Array
(
)
Array
(
[unsetindex]=>
)

Anyforeachorsimilarwillbedifferentbeforeandafterthecall.
up
down
11
anonymousleafatgmaildotcom
9yearsago
issetexpectsthevariablesignfirst,soyoucan'taddparenthesesoranything.

<?php
$foo=1;
if(isset(($foo))){//Syntaxerroratisset((
$foo=2;
http://php.net/manual/es/function.isset.php 12/32
26/4/2017 PHP:issetManual

}
?>
up
down
3
andreasonny83atgmaildotcom
1yearago
Hereisanexamplewithmultipleparameterssupplied

<?php
$var=array();
$var['val1']='test';
$var['val2']='on';

if(isset($var['val1'],$var['val2'])&&$var['val2']==='on'){
unset($var['val1']);
}
print_r($var);
?>

Thiswilloutput:
Array
(
[val2]=>on
)

Thefollowingcodedoesthesamecalling"isset"2times:

<?php
$var=array();
$var['val1']='test';
$var['val2']='on';

if(isset($var['val1'])&&isset($var['val2'])&&$var['val2']==='on'){
unset($var['val1']);
}
print_r($var);
?>
up
down
9
adotschaffhirtatsednasoftdotde
8yearsago
Youcansafelyuseissettocheckpropertiesandsubpropertiesofobjectsdirectly.Soinsteadof
writing

isset($abc)&&isset($abc>def)&&isset($abc>def>ghi)

orinashorterform

isset($abc,$abc>def,$abc>def>ghi)

youcanjustwrite

http://php.net/manual/es/function.isset.php 13/32
26/4/2017 PHP:issetManual

isset($abc>def>ghi)

withoutraisinganyerrors,warningsornotices.

Examples
<?php
$abc=(object)array("def"=>123);
var_dump(isset($abc));//bool(true)
var_dump(isset($abc>def));//bool(true)
var_dump(isset($abc>def>ghi));//bool(false)
var_dump(isset($abc>def>ghi>jkl));//bool(false)
var_dump(isset($def));//bool(false)
var_dump(isset($def>ghi));//bool(false)
var_dump(isset($def>ghi>jkl));//bool(false)

var_dump($abc);//object(stdClass)#1(1){["def"]=>int(123)}
var_dump($abc>def);//int(123)
var_dump($abc>def>ghi);//null/E_NOTICE:Tryingtogetpropertyofnonobject
var_dump($abc>def>ghi>jkl);//null/E_NOTICE:Tryingtogetpropertyofnonobject
var_dump($def);//null/E_NOTICE:Tryingtogetpropertyofnonobject
var_dump($def>ghi);//null/E_NOTICE:Tryingtogetpropertyofnonobject
var_dump($def>ghi>jkl);//null/E_NOTICE:Tryingtogetpropertyofnonobject
?>
up
down
7
Anlzselgin
7yearsago
Note:Becausethisisalanguageconstructandnotafunction,itcannotbecalledusingvariable
functions.

Sowhyitisunder"VariablehandlingFunctions".Maybethereshouldbesomegooddocumentationfield
forlanguageconstructs.
up
down
8
soywizatphpdotnet
11yearsago
Sometimesyouhavetocheckifanarrayhassomekeys.Toachieveityoucanuse"isset"likethis:
isset($array['key1'],$array['key2'],$array['key3'],$array['key4'])
Youhavetowrite$arrayalltimesanditisreiterativeifyouusesamearrayeachtime.

Withthissimplefunctionyoucancheckifanarrayhassomekeys:

<?php
functionisset_array(){
if(func_num_args()<2)returntrue;
$args=func_get_args();
$array=array_shift($args);
if(!is_array($array))returnfalse;
foreach($argsas$n)if(!isset($array[$n]))returnfalse;
returntrue;
}
?>
http://php.net/manual/es/function.isset.php 14/32
26/4/2017 PHP:issetManual

Use:isset_array($array,'key1','key2','key3','key4')
Firstparameterhasthearray;followingparametershasthekeysyouwanttocheck.
up
down
4
uramihsayibok,gmail,com
4yearsago
Notethatisset()isnotrecursiveasofthe5.4.8Ihaveavailableheretotestwith:ifyouuseit
onamultidimensionalarrayoranobjectitwillnotcheckisset()oneachdimensionasitgoes.

Imagineyouhaveaclasswithanormal__issetanda__getthatfatalsfornonexistantproperties.
isset($object>nosuch)willbehavenormallybutisset($object>nosuch>foo)willcrash.Ratherharsh
IMObutstillpossible.

<?php

classFatalOnGet{

//pretendthatthemethodshaveimplementationsthatactuallytrytodowork
//inthisexampleIonlycareabouttheworstcaseconditions

publicfunction__get($name){
echo"(getting{$name})";

//ifpropertydoesnotexist{
echo"Propertydoesnotexist!";
exit;
//}
}

publicfunction__isset($name){
echo"(isset{$name}?)";
//returnwhetherthepropertyexists
returnfalse;
}

$obj=newFatalOnGet();

//works
echo"Testingif>nosuchexists:";
if(isset($obj>nosuch))echo"Yes";elseecho"No";

//fatals
echo"\nTestingif>nosuch>fooexists:";
if(isset($obj>nosuch>foo))echo"Yes";elseecho"No";

//notexecuted
echo"\nTestingif>irrelevantexists:";
if(isset($obj>irrelevant))echo"Yes";elseecho"No";

?>
http://php.net/manual/es/function.isset.php 15/32
26/4/2017 PHP:issetManual

Testingif>nosuchexists:No
Testingif>nosuch>fooexists:Propertydoesnotexist!

Uncommenttheechosinthemethodsandyou'llseeexactlywhathappened:

Testingif>nosuchexists:(issetnosuch?)No
Testingif>nosuch>fooexists:(gettingnosuch)Propertydoesnotexist!

Onasimilarnote,if__getalwaysreturnsbutinsteadissueswarningsornoticesthenthosewill
surface.
up
down
5
CuongHuyTo
6yearsago
1)Notethatisset($var)doesn'tdistinguishthetwocaseswhen$varisundefined,orisnull.
Evidenceisinthefollowingcode.

<?php
unset($undefined);
$null=null;
if(true===isset($undefined)){echo'isset($undefined)===true'}else{echo'isset($undefined)===
false');//'isset($undefined)===false'
if(true===isset($null)){echo'isset($null)===true'}else{echo'isset($null)===false');
//'isset($null)===false'
?>

2)Ifyouwanttodistinguishundefinedvariablewithadefinedvariablewithanullvalue,thenuse
array_key_exist

<?php
unset($undefined);
$null=null;

if(true!==array_key_exists('undefined',get_defined_vars())){echo'$undefineddoesnotexist';}
else{echo'$undefinedexists';}//'$undefineddoesnotexist'
if(true===array_key_exists('null',get_defined_vars())){echo'$nullexists';}else{echo'$null
doesnotexist';}//'$nullexists'
?>
up
down
4
qeremy
5yearsago
Simplesolutionfor:"Fatalerror:Can'tusefunctionreturnvalueinwritecontextin..."

<?php
function_isset($val){returnisset($val);}
?>
up
down
5
Ashus
http://php.net/manual/es/function.isset.php 16/32
26/4/2017 PHP:issetManual

8yearsago
Notethatarraykeysarecasesensitive.

<?php
$ar['w']=true;

var_dump(isset($ar['w']),
isset($ar['W']));
?>

willreport:
bool(true)bool(false)
up
down
5
randallgirardathotmaildotcom
10yearsago
Theunexpectedresultsofissethasbeenreallyfrustratingtome.Hence,itdoesn'tworkhowyou'd
thinkitwould,(asdocumented)avarcurrentlyinthescopewithanullvaluewillreturnfalse.

Heresaquicksolution,perhapstherearebetterwaysofgoingaboutthis,butheresmysolution...

<?php
functionis_set($varname,$parent=null){
if(!is_array($parent)&&!is_object($parent)){
$parent=$GLOBALS;
}
returnarray_key_exists($varname,$parent);
}
?>

Hence,$varnameshouldbeamixedvalueofvar'stocheckfor,and$parentcanbeanarrayorobject,
whichwilldefaulttotheGLOBALscope.Seethedocumentationofarray_key_existsforfurther
information.

Thiswillallowtocheckifavarisinthecurrentscope,object,orarray...Whetherit'sanull,
false,true,oranyvalue.ItdependsonARRAY_KEY_EXISTSforit'sfunctionalitywhichalsoworks
withObjects.Feelfreetoimproveonthisanyone;D
up
down
4
packard_bell_necathotmaildotcom
9yearsago
Note:isset()onlychecksvariablesasanythingelsewillresultinaparseerror.Inotherwords,
thefollowingwillnotwork:isset(trim($name)).

isset()istheoppositeofis_null($var),exceptthatnowarningisgeneratedwhenthevariableis
notset.
up
down
4
talbutt(at)mail(dot)med(dot)upenn(edu)
9yearsago
InPHP5.2.3,reallyreturnstrueifthevariableissettonull.
http://php.net/manual/es/function.isset.php 17/32
26/4/2017 PHP:issetManual

up
down
4
TeeCee
10yearsago
Inresponseto10Feb200606:02,isset($v)isinall(exceptpossiblybuggy)casesequivalentto
!is_null($v).Andno,itdoesn'tactuallytestifavariableissetornotbymydefinition"$vis
setifunset($v)hasnoeffect".

<?php
unset($c);//force$ctobeunset
var_dump($a=&$c);//NULL,butthisactuallysets$aand$ctothe'same'NULL.
var_dump(isset($c));//bool(false)
var_dump($a=5);//int(5)
var_dump($c);//int(5)

unset($c);
var_dump($a=&$c);//NULL
var_dump(isset($c));//bool(false)
unset($c);
var_dump($a=5);//int(5)
var_dump($c);//NULL
?>

Inthefollowingexample,weseeanalternatemethodoftestingifavariableisactuallysetornot:
<?php
var_dump(array_key_exists('c',get_defined_vars()));//false
var_dump(isset($c));//alsofalse
var_dump($c);//manipulate$cabit...
var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars()));//...stillfalse
var_dump($c=NULL);//thissets$c
var_dump(array_key_exists('c',get_defined_vars()));//true!
var_dump(isset($c));//false;isset()stillsaysit'sunset
unset($c);//actuallyunsetit
var_dump(array_key_exists('c',get_defined_vars()));//false
var_dump($a=&$c);
var_dump(array_key_exists('c',get_defined_vars()));//true!
unset($c);//unsetitagain
var_dump(&$c);//&NULL
var_dump(array_key_exists('c',get_defined_vars()));//true!
?>

Obviously,nullvaluestakeupspace(ortheywouldn'tshowupinget_defined_vars).Also,notethat
&$vsets$vtoNULLifitisunset.
up
down
3
tomek
8yearsago
Here'sasimplefunctiontotestifthevariableisset:

http://php.net/manual/es/function.isset.php 18/32
26/4/2017 PHP:issetManual

<?php
functionis($var)
{
if(!isset($var))returnfalse;
if($var!==false)returntrue;
returnfalse;
}
?>

Nowinsteadofverypopular(butinvalidinmanysituations):

if(!$var)$var=5;

youcanwrite:

if(!is($var))$var=5;
up
down
3
markdotfabrizioatgmaildotcom
8yearsago
Iknowthisisprobablynottherecommendedwaytodothis,butitseemstoworkfineforme.Instead
ofthenormalissetchecktoextractvariablesfromarrays(like$_REQUEST),youcanusethe@prefix
tosquelchanyerrors.

Forexample,insteadof:
<?php
$test=isset($_REQUEST['test'])?$_REQUEST['test']:null;
?>
youcanuse:
<?php
$test=@$_REQUEST['test'];
?>

Itsavessometyping,butdoesn'tgivetheopportunitytoprovideadefaultvalue.If'test'isnot
anassignedkeyfor$_REQUEST,theassignedvaluewillbenull.
up
down
2
benallfreeatgmaildotcom
6yearsago
isset()returnsTRUEifavalueisNULL.Thatseemswrongtomeasthereisnowaytodistinguish
betweenavaluesettoNULLandatrulyundefinedvalue.

Ifyouhavethisprobleminsideaclass,thereisafix:

<?php
classT
{
function__isset($att)
{
$props=get_object_vars($this);
returnarray_key_exists($att,$props);
}
http://php.net/manual/es/function.isset.php 19/32
26/4/2017 PHP:issetManual

$x=newT();
$x>foo_exists=4;

var_dump(isset($x>foo_exists));//TRUE
var_dump(isset($x>bar_exists));//FALSE
?>
[EDITORthiagoNOTE:Thissnippethasimprovementsby"PaulLashbrook"]
up
down
0
RobertdotVanDellatcbsdotcom
7yearsago
Here'sanicelittlefunctionthatIuseeverywherethat'llhelpwithsettingalternatevaluessoyou
don'thaveabunchofsituationslike:

<?php
if(isset($a))
{
$b=$a;
}
else
{
$b="default";
}

functionisset_or(&$check,$alternate=NULL)
{
return(isset($check))?$check:$alternate;
}

//Exampleusage:
$first_name=isset_or($_POST['first_name'],"Empty");
$total=isset_or($row['total'],0);

?>
up
down
2
marcioatsuhdodotcom
3yearsago
//thinwaytosetavariable
$foo=isset($_POST['foo'])?$_POST['foo']:null;
up
down
1
beucatbeucdotnet
10yearsago
Bewarethatthechk()functionbelowcreatesthevariableorthearrayindexifitdidn'texisted.

<?php
functionchk(&$var){
if(!isset($var))
http://php.net/manual/es/function.isset.php 20/32
26/4/2017 PHP:issetManual

returnNULL;
else
return$var;
}

echo'<pre>';
$a=array();
var_dump($a);
chk($a['b']);
var_dump($a);
echo'</pre>';

//Gives:
//array
//empty
//
//array
//'b'=>null
?>
up
down
3
onnoatitmazedotcomdotau##php==owh
11yearsago
InPHP4,thefollowingworksasexpected:

<?php
if(isset($obj>thing['key'])){
unset($obj>thing['key']);
}
?>

InPHP5howeveryouwillgetafatalerrorfortheunset().

Theworkaroundis:

<?php
if(is_array($obj>thing)&&isset($obj>thing['key'])){
unset($obj>thing['key']);
}
?>
up
down
5
soapergematgmaildotcom
8yearsago
BelowauserbythenameofScottpostedanisval()function;Ijustwantedtopointoutarevision
tohismethodsinceit'sabitlengthyforwhatitdoes.ThetrickistorealizethatabooleanAND
clausewillterminatewithfalseassoonasitencountersanythingthatevaluatestofalse,andwill
skipoveranyremainingchecks.

Insteadoftakingupthespacetodefineisval(),youcouldjustruninlinecommandsforeach
variableyouneedtocheckthis:

http://php.net/manual/es/function.isset.php 21/32
26/4/2017 PHP:issetManual

<?php

$isval=isset($_POST['var'])&&!empty($_POST['var']);

?>

Alsobewarnedthatifyoutrytoencapsulatethisintoafunction,youmightencounterproblems.
It'smeanttostandalone.
up
down
4
pianistsk8eratgmaildotcom
12yearsago
ThisfunctionisveryusefulwhilecallingtotheURLtospecifywhichtemplatetobeusedoncertain
partsofyourapplication.

Hereisanexample...

<?php

$cat=$_GET['c'];
$id=$_GET['id'];
$error='templates/error.tpl';

if(isset($cat))
{
if(isset($id))
{
$var='templates/pics/'.$cat.''.$id.'.tpl';
if(is_file($var))
{
include($var);
}
else
{
include($error);
}
}
else
{
$var='templates/pics/'.$cat.'.tpl';
if(is_file($var))
{
include($var);
}
else
{
include($error);
}
}
}
else
{
include('templates/alternative.'.tpl);
http://php.net/manual/es/function.isset.php 22/32
26/4/2017 PHP:issetManual

?>

Youcanseeseveralusesoftheissetfunctionbeingusedtospecifywheteratemplateistobe
calleduponornot.ThiscaneasilypreventothergenericPHPerrors.
up
down
6
robertoatspadimdotcomdotbr
10yearsago
test:

<?php
$qnt=100000;
$k=array();
for($i=0;$i<$qnt;$i++)
$k[$i]=1;

echomicrotime()."\n";
for($i=0;$i<$qnt;$i++)if(isset($k[$i]));
echomicrotime()."\n";
for($i=0;$i<$qnt;$i++)if(array_key_exists($i,$k));
echomicrotime()."\n";
for($i=0;$i<$qnt;$i++)if($k[$i]==1);
echomicrotime()."\n";

?>

theinterestingresult:
issetisthefastest
up
down
2
ayyappandotashokatgmaildotcom
1yearago
ReturnValues:
ReturnsTRUEifvarexistsandhasvalueotherthanNULL,FALSEotherwise.

<?php
$a=NULL;
$b=FALSE;//TheoutputwasTRUE.
$c=TRUE;
$d='';
$e="";
if(isset($b)):
echo"TRUE";
else:
echo"FALSE";
endif;
?>
Couldanyoneexplainmeinclarity.
up
down
http://php.net/manual/es/function.isset.php 23/32
26/4/2017 PHP:issetManual

8
soapergematgmaildotcom
8yearsago
Itispossibletoencapsulateisset()callsinsideyourownfunctionsifyoupassthembyreference
(notetheampersandintheargumentlist)insteadofbyvalue.Aprimeexamplewouldbetheheavily
requested"ifsetor"function,whichwillreturnavaluewhenitisset,otherwiseadefaultvalue
thattheuserspecifiesisused.

<?php

functionifsetor(&$val,$default=null)
{
returnisset($val)?$val:$default;
}

//exampleusage
$id=intval(ifsetor($_GET['id'],0));

?>
up
down
4
flobee
3yearsago
KISS:array_key_exists()isoftentheanswer,notisset()
<?php
$array['secure']=null;
if(isset($array['secure'])){
//whathappenshere?
}?>
up
down
8
kariedoo
11yearsago
Before:

//ask,ifisset
$number=isset($_GET['number'])?$_GET['number']:'';
$age=isset($_GET['age'])?$_GET['age']:'';
$street=isset($_GET['street'])?$_GET['street']:'';

After:>it'seasiertoread

//ask,ifisset
$parameter=array('number','age','street');
foreach($parameteras$name)
{
$$name=isset($_GET[$name])?$_GET[$name]:'';
}
up
down
8
Anonymous
http://php.net/manual/es/function.isset.php 24/32
26/4/2017 PHP:issetManual

11yearsago
Idon'tknowifyouguyscanusethisbutifindthispieceofcodeprettyuseful(forreadabillity
atleast):

functionisset_else($&v,$r)
{
if(isset($v))
return$v;
else
return$r;
}

Thiswayyoucango:

$a=4;

$c+=isset_else($a,0);
$c+=isset_else($b,0);

echo$c;

Ofcourse,thiscodewouldworkanyway,butyougetthepoint.
up
down
8
jcdotmichelatsymetriedotcom
12yearsago
Using
isset($array['key'])
isuseful,butbecareful!
using
isset($array['key']['subkey'])
doesn'tworkasonecouldexpect,if$array['key']isastringitseemsthat'subkey'isconvertedto
(integer)0and$array['key']['subkey']isevaluatedasthefirstcharofthestring.
Thesolutionistouse
is_array($array['key'])&&isset($array['key']['subkey'])

Hereisasmallcodetoshowthis:

<?php
$ex=array('one'=>'val1','two'=>'val2');
echo'$ex=';print_r($ex);
echo"<br/>";

echo"isset(\$ex['one']['three']):";
if(isset($ex['one']['three']))
echo'true';
else
echo'false';

echo"<br/>";
echo"is_array(\$ex['one'])&&isset(\$ex['one']['three']):";
if(is_array($ex['one'])&&isset($ex['one']['three']))
echo'true';
http://php.net/manual/es/function.isset.php 25/32
26/4/2017 PHP:issetManual

else
echo'false';
?>

shows:
$ex=Array([one]=>val1[two]=>val2)
isset($ex['one']['three']):true
is_array($ex['one'])&&isset($ex['one']['three']):false
up
down
3
ohccat163dotcom
1yearago
Whenavariableissetanditsvaluesisnull,isset()returnsfalse.

Youcanusearray_key_exists()tocheckwhetheranullvaluevariableexists.

<?php
$wxc=null;
var_dump(isset($wxc));
var_dump(array_key_exists('wxc',$GLOBALS));
?>

Outputoftheaboveexample:

bool(false)bool(true)
up
down
11
black__rayatmywaydotcom
9yearsago
if(isset($_POST['in_qu']))
{

include("qanda/in_qu.php");
$content.=$message;
include("qanda/view_qanda.php");
}
elseif(isset($_GET['rq']))
{
include("qanda/add_answer.php");
}
elseif(isset($_POST['add_answer']))
{
include("qanda/in_an.php");
$content.=$message;
include("qanda/view_qanda.php");
}
elseif($_GET['act']=='v_qanda'&&!(isset($_GET['rq'])))
{
include("qanda/view_qanda.php");
}
/*
if(isset($_POST['add_answer']))
http://php.net/manual/es/function.isset.php 26/32
26/4/2017 PHP:issetManual

up
down
12
samb
9yearsago
Checkoutthisifsetorfunction.If$varisset,donothing,otherwise$var=$default.

<?php

$name=ifsetor($name,'defaultname');

functionifsetor(&$var,$default)
{
returnisset($var)?$var:$default);
}

?>
up
down
13
i[at]nemoden[dot]com
6yearsago
Simple,butveryuseful:

<?php
functionissetOr($var,$or=false){
returnisset($var)?$var:$or;
}
?>

Someexamples:
<?php
$a='1';
$b='2';
echoissetOr($a,issetOr($b,3));//1
?>
<?php
$b='2';
echoissetOr($a,issetOr($b,3));//2
?>
<?php
echoissetOr($a,issetOr($b,3));//3
?>
up
down
15
johnatdarvendotcodotuk
5yearsago
Itisworthnotingthatinordertocheckfortheexistenceofakeywithinanarray,regardlessof
it'scontentsoneshouldusearray_key_exists()notisset().

isset()will(correctly)returnfalseifthevalueofyourarraykeyisnull,whichmaybea
perfectlyvalidcondition.
up
http://php.net/manual/es/function.isset.php 27/32
26/4/2017 PHP:issetManual

down
16
gonchaloxatgmaildotcom
5yearsago
Usefultocheckifthevariablehavesomevalue...speciallyforGETPOSTvariables

<?php
functionisset_or(&$check,$alternate=NULL)
{
return(isset($check))?(empty($check)?$alternate:$check):$alternate;
}

functiongetGETPOST($var)
{
returnisset_or($_GET[$var],isset_or($_POST[$var],"Empty"));
}
?>

Example
echogetGETPOST('na');//Findthenavarriablbygetandpost
up
down
5
ericgatartywebdesigndotcom
1yearago
Ifoundsomethinginterestingwhileworkingwithisset()inPHP5.5+

<?php

$a="foo";
$b="bar";

var_dump(isset($a,$b));//returnstrue

unset($b);

var_dump(isset($a,$b));//returnsfalse(asexpected);

...BUT...
var_dump(!isset($a,$b));//STILLreturnstrue!
up
down
17
jon
13yearsago
SincePHPwillcheckcasesinorder,Ioftenendupusingthisbitofcode:

<?php
if(isset($var)&&$var){
//dosomething
}
?>

Inshort,ifyouhaveerrorreportingon,and$varisnotset,PHPwillgenerateanerrorifyoujust
http://php.net/manual/es/function.isset.php 28/32
26/4/2017 PHP:issetManual

have:

<?php
if($var){//dosomething}
?>

...but,asnotedelsewhere,willreturnTrueifsettoFalseinthiscase:
<?php
if(isset($var)){//dosomething}
?>

Checkingbothtoseeif$varisset,andthatitequalssomethingotherthanNullorFalseis
somethingIfindveryusefulalotoftimes.If$varisnotset,PHPwillneverexecutethesecond
partof"(isset($var)&&$var)",andthusnevergenerateanerroreither.

Thisalsoworksveryniceforsettingvariableaswell,e.g.:
<?php
$var=(isset($var)&&$var)?$var:'newvalue';
?>
up
down
1
kurdtpageatgmaildotcom
4monthsago
Thenew(asofPHP7)'nullcoalesceoperator'allowsshorthandisset.Youcanuseitlikeso:

<?php
//Fetchesthevalueof$_GET['user']andreturns'nobody'
//ifitdoesnotexist.
$username=$_GET['user']??'nobody';
//Thisisequivalentto:
$username=isset($_GET['user'])?$_GET['user']:'nobody';

//Coalescingcanbechained:thiswillreturnthefirst
//definedvalueoutof$_GET['user'],$_POST['user'],and
//'nobody'.
$username=$_GET['user']??$_POST['user']??'nobody';
?>

Quotedfromhttp://php.net/manual/en/migration70.newfeatures.php#migration70.newfeatures.null
coalesceop
up
down
23
davidatthegallagherdotnet
5yearsago
Justtoreiterateonwhateveryonehasalreadysaidbefore,youshouldnotusewrapperfunctionsfor
isset.UsingawrapperfunctionwillgenerateaNoticeunlessyoupasstheunsetvariableby
reference,inwhichcaseitistheequivalenttowritingusing$var===null(whichisalotfaster).
Evenifyoudopassthevariablebyreference,youcouldstillgetnoticesusingmultidimensional
arrayswhereisset()wouldsilentlyreturnfalse.
up
down
26
http://php.net/manual/es/function.isset.php 29/32
26/4/2017 PHP:issetManual

jwvdveeratgmaildotcom
8yearsago
Hereashortnoteonthefunctiontomekwrote:
Don'tuseit,becauseitisstillbettertouse!$varthan!is($var).

Somecommentsonthebodyofthefunction:
<?php
functionis($var)
{
if(!isset($var))returnfalse;#Variableisalwaysset...OtherwisePHPwouldhavethrownanerror
oncall.
if($var!==false)returntrue;#So,0,NULL,andsomeothervaluesmaynotbehavelikeisNot?And
whataboutthedifferencebetweenaclassandNULL?
returnfalse;
}
?>

Thereasonwhyyoushallnotusethisfunction:
Notice:Undefinedvariable:{variablename}in{file}online{__LINE__}

It'smeasplainasthenoseonyourfacethatthepieceofcodehasn'tbeentestedwithE_NOTICE.

Somyadviceinthiscaseis:don'tusetheabovefunction,butsimplyuse!,andfunctionssuchlike
is_nullinthesituationtheyaremadefor.
up
down
29
phpnetdot5dotreinhold2000attspamgourmetdotcom
12yearsago
ifyouwanttocheckwhethertheuserhassentpostvarsfromaform,itisapaintowritesomething
likethefollowing,sinceisset()doesnotcheckforzerolengthstrings:

if(isset($form_name)&&$form_name!='')[...]

ashorterwaywouldbethisone:

if($form_name&&$form_message)[...]

butthisisdirtysinceyoucannotmakesurethesevariablesexistandphpwillechoawarningifyou
refertoanonexistingvariablelikethis.plus,astringcontaining"0"willevaluatetoFALSEif
castedtoaboolean.

thisfunctionwillcheckoneormoreformvaluesiftheyaresetanddonotcontainanemptystring.
itreturnsfalseonthefirstemptyornonexistingpostvar.

<?
functionpostvars(){
foreach(func_get_args()as$var){
if(!isset($_POST[$var])||$_POST[$var]==='')returnfalse;
}
returntrue;
}
?>

http://php.net/manual/es/function.isset.php 30/32
26/4/2017 PHP:issetManual

example:if(postvars('form_name','form_message'))[...]
up
down
33
richardwilliamleeATgmail
11yearsago
Justanoteontheprevioususerscomments.isset()shouldonlybeusedfortestingifthevariable
existsandnotifthevariablecontainesanempty""string.empty()isdesignedforthat.

Also,asnotedpreviosuly!empty()isthebestmethodfortestingforsetnonemptyvariables.
addanote

Funcionesdemanejodevariables
boolval
debug_zval_dump
doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_bool
is_callable
is_double
is_float
is_int
is_integer
is_iterable
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
isset
print_r
serialize
settype
strval
unserialize
unset
var_dump
var_export

Copyright20012017ThePHPGroup
MyPHP.net
Contact
OtherPHP.netsites
http://php.net/manual/es/function.isset.php 31/32
26/4/2017 PHP:issetManual

Mirrorsites
Privacypolicy

http://php.net/manual/es/function.isset.php 32/32

You might also like