Tuesday 12 June 2012

Php isset


isset

(PHP 4, PHP 5)
issetDetermine if a variable is set and is not NULL

reject note Description

bool isset ( mixed $var [, mixed $... ] )
Determine if a variable is set and is not NULL.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

reject note Parameters

var
The variable to be checked.
...
Another variable ...

reject note Return Values

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

reject note Changelog

VersionDescription
5.4.0
Checking non-numeric offsets of strings now returns FALSE

Example #1 isset() Examples
<?php

$var 
'';
// This will evaluate to TRUE so the text will be printed.if (isset($var)) {
    echo 
"This var is set so I will print.";
}
// In the next examples we'll use var_dump to output
// the return value of isset().
$a "test";$b "anothertest";
var_dump(isset($a));      // TRUEvar_dump(isset($a$b)); // TRUE
unset ($a);
var_dump(isset($a));     // FALSEvar_dump(isset($a$b)); // FALSE
$foo NULL;var_dump(isset($foo));   // FALSE
?>


This also work for elements in arrays:

<?php

$a 
= array ('test' => 1'hello' => NULL'pie' => array('a' => 'apple'));
var_dump(isset($a['test']));            // TRUEvar_dump(isset($a['foo']));             // FALSEvar_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try: 
var_dump(array_key_exists('hello'$a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUEvar_dump(isset($a['pie']['b']));        // FALSEvar_dump(isset($a['cake']['a']['b']));  // FALSE
?>

Example #2 isset() on String Offsets
PHP 5.4 changes how isset() behaves when passed string offsets.
<?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['0 Mostel']));?>
Output of the above example in PHP 5.3:
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
Output of the above example in PHP 5.4:
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)


        

No comments:

Post a Comment