Section 5.0. Introduction

5.0. Introduction

Along with conditional logic, variables are the core of what makes computer programs powerful and flexible. If you think of a variable as a bucket with a name that holds a value, PHP lets you have plain old buckets, buckets that contain the name of other buckets, buckets with numbers or strings in them, buckets holding arrays of other buckets, buckets full of objects, and just about any other variation on that analogy you can think of.

A variable is either set or unset. A variable with any value assigned to it, TRue or false, empty or nonempty, is set. The function isset( ) returns true when passed a variable that's set. To turn a variable that's set into one that's unset, call unset( ) on the variable or assign null to the variable. Scalars, arrays, and objects can all be passed to unset( ). You can also pass unset( ) multiple variables to unset them all:

unset($vegetables); unset($vegetables[12]); unset($earth, $moon, $stars);

If a variable is present in the query string of a URL, even if it has no value assigned to it, it is set. Thus:

sets $_GET['monkeys'] to 12 and $_GET['chimps'] to the empty string.

All unset variables are also empty . Set variables may be empty or nonempty. Empty variables have values that evaluate to false as a boolean: the integer 0, the double 0.0, the empty string, the string "0", the boolean false, an array with no elements, an object with no properties (in versions of PHP prior to PHP 5) and NULL. Everything else is nonempty. This includes the string "00", and the string " ", containing just a space character.

Variables evaluate to either true or false. The values listed earlier that evaluate to false as a boolean are the complete set of what's false in PHP. Every other value is true. The distinction between empty and false is that emptiness is only possible for variables.

Constants and return values from functions can be false, but they can't be empty. For example, Example 5-1 shows a valid use of empty( ) because $first_name is a variable.

Correctly checking if a variable is empty

if (empty($first_name)) { .. }

On the other hand, the code in Example 5-2 returns parse errors because 0 (a constant) and the return value from get_first_name( ) can't be empty.

Incorrectly checking if a constant is empty

if (empty(0)) { .. } if (empty(get_first_name())) { .. }

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: