ExpertRefresh

Variables / Check  

Related Pages

Definition
Variable
Check
Type casting
Array to object
New object


0.0% 100%
 
 
0 pages 298 questions
1) What will the following script output? <?php $a = 1; $b = 'n'; echo isset($a) && !empty(trim($b));





2) Which is better when checking that variable $a exists and is not null?







One of the downsides of the way PHP handles variables is that there is no way to ensure that any one of them will exist at any given point in the execution of a script. A call to isset() will return TRUE if a variable exists and has a value other than NULL A call to empty() will returns TRUE if var has a empty and zero value ("", 0, NULL) <?php if(isset($_POST['myField']) && $_POST[myField] != "") ... code if(!empty($_POST['myField'])) // a more efficient way ... code <?php error_reporting(E_ALL); if ($a) echo 'Yes'; // Notice: Undefined variable: a if (!empty($a)) echo 'Yes'; // Output: nothing (better) isset() - Determine if a variable is set and is not NULL <?php $a = 1; $b = 0; $c = ""; $d = null; echo isset($a); // TRUE echo isset($a, $b); // TRUE echo isset($a, $b, $c); // TRUE echo isset($a, $b, $c, $d); // FALSE empty() - Determine whether a variable is empty <?php // Determine whether a variable is considered to be empty $a = ""; echo empty($a); // TRUE $a = 0; echo empty($a); // TRUE $a = "0"; echo empty($a); // TRUE $a = NULL; echo empty($a); // TRUE $a = FALSE; echo empty($a); // TRUE $a = array(); echo empty($a); // TRUE // Only checks variables as anything else will result in a parse error $a = 1; empty(trim($a)); // Fatal error


References