PHP Variable Functions

PHP provides over thirty functions that can perform various functions related to variables. Most are beyond the scope of this tutorial, but several are useful, and even necessary to know.

Before we learn about the functions, let's take a look at the different types of data that can be stored in variables. Although PHP automatically assigns the data type of each variable based on the data that it contains, it will be good to know a little about each one.

Type Type Description
String Scalar Sequences of Characters, Such As This Statement
Integer Scalar Whole Number, Positive or Negative, Without a Decimal Point
Float (Also Floating-Point or Double) Scalar Floating Numbers, With a Decimal Point
Boolean Scalar Has Only Two Possible Values: "TRUE" or "FALSE"
Array Compound Named/Indexed Collection of Other Values
Object Compound Programmer-Defined Classes
Resource Special Hold References to External Resources (Database Connections, Etc.)
NULL Special Has Only One Possible Value: NULL

Got all that? I didn't either when it was first introduced to me, and I've never really needed it, so let's move on.

Probably the most commonly used variable function is the isset() function, and, as the name implies, it can tell you whether or not a variable has been set.

<?php
  $question = "What's the unluckiest kind of cat to have?<br>";
  if (isset($question)) {
    echo $question;
    echo "A catastrophe!";
  } else {
    echo "If you don't have a question you don't get an answer.";
  }
?>

The empty() function will determine whether or not a variable contains actual data. An empty string "", 0, NULL & FALSE are all considered empty variables.

<?php
  $question = "What do you get when two giraffes collide?<br>";
  if (!empty($question)) {
    echo $question;
    echo "A giraffic jam.";
    unset($question);
  } else {
    echo "If you don't have a question you don't get an answer.";
  }
?>

The unset() function, confusingly stuck in the example above, will unset the variable so that it is not longer set. It can be reset later in the script, but until then it no longer exists.

Below are these and a few other variable functions that can be useful.

Function Description
isset() Determines If a Variable Is Set and Is Not NULL
empty() Determines Whether a Variable Is Empty
gettype() Gets the Type of a Variable
settype() Sets the Type of a Variable
unset() Unsets a Given Variable

A complete list of the variable functions available can be found in the official PHP manual. Each function includes examples that will help you understand how to use it.