• home
  • forum
  • my
  • kt
  • download
  • Variables in PHP

    Author: 2009-03-09 09:51:37 From:

    Variables are probably one of the most commonly used code constructs you’ll come across while programming. If you have any experience of mathematics, especially algebra, you’ll be aware of the concept of using symbols to represent unknown quantities in equations, like in the following example
    x + 5 = 7;
    from this we can deduce that x = 2

    In PHP it works in a similar fashion, except we usually know the value of x, and simply assign it a specific value, such as x = 5. We can then use that value to perform calculations using other symbols and numbers. For example

    $x = 5  //x now equals 5
    $y = $x + 10  /* y now equals 5 + 10 */

    These symbols in PHP are known as variables and require you to follow a specific syntax to use them properly. Once you understand the principles behind them, you’ll begin to see how they form a major component of any PHP application, and can be used to store many things other than just numbers. Let us begin though, by guiding you through a few simple examples of the use of variables.

    A simple introduction

    A very simple example of the use of a variable in PHP is to hold just one number, e.g.

    $x = 5;

    All variables in PHP start with a dollar sign, followed by a string of numbers, letters (both lower-case and capitals) and underscores. Variables are also case sensitive, meaning that $Variable is not equal to $variable. The only other requirement of variable naming is that the first digit cannot be a number. These are examples of valid variable names

    $variable_name = 5; //valid - integer
    $VariableName = 25.5; //valid - floating point
    $variable3 = 155; //valid
    $_variable_number_four = "value"; //valid - string
    $_x = "five"; //valid

    These are not valid variable names

    $1st_variable = 5; //invalid
    $Variable.name = 25; //invalid, cannot have dots in names

    Variables are assigned values through the use of the equals sign (=) operator. Once a variable has been assigned to a value, that variable symbol can be used in place of the value anywhere in the code. The value of the variable can also be changed at any point during the execution of the code. The same value can also be assigned to multiple variables at the same time, like so

    $a = $b = $c = 5;
    echo "$a, $b, $c";

    This produces the output

    5, 5, 5

    Flexible Types

    The “type” of a variable is defined by the value you’ve assigned to it. PHP supports a wide range of types, including strings, integers and floats.

    $string = "This is a string";
    $integer = 5; //an integer value;
    $float = 4.55; //a "floating point" value

    PHP doesn’t explicitly require that you maintain the same type for a certain variable though. If you tried to assign a string value to a variable which previously contained an integer, you’ll encounter no problems. Similarly with any other types, floating point variables can hold integers or strings and so on.

    Strings in PHP

    A string in PHP is a variable holding zero or more characters of text, and can be used to store words or sentences to be inserted into the body of a web-page, or to be used in the result of calculations. Strings are specified by wrapping a section of text in single or double quotes. Here are some examples of valid string variables.

    $str1 = "This is a string";
    $str2 = 'This also works';
    $str3 = "Splitting strings between lines
     is also acceptable";

    Here are some considerations to bear in mind when assigning strings

    • The start and end quotes must be of matching types - you cannot mix single and double quotes. This code is invalid

      $str1 = "This code will break';
      

    Escaping characters

    If you’re using single or double quotes within the string itself, this can cause complications. Take the following as an example

    $str1 = 'Don't use unescaped quotes'; /* this will break */
    

    Here, the use of the single quote within the string makes PHP think you’re terminating the string after “Don”, and then it expects a semicolon directly after. In this case, the sentence continues and so the code breaks.

    A solution to this is to escape the offending character. This is done via the use of the backslash (\) character immediately before. Like so

    $str1 = 'Don\'t use unescaped quotes'; /* this is now valid code */

    This tells PHP to treat the single quote as if it were a character to be printed, rather than an element of the PHP syntax to be processed.

    You will also encounter this problem if you try and use the dollar ($) symbol inside strings. Because of the way PHP allows variables to be inserted into strings (and this will be explained further shortly), PHP will interpret any use of the dollar symbol as an attempt to insert a variable. Note that this only happens when using double quotes. For example

    $string = "Hello world";
    $str1 = "$string"; /* will output - Hello world */
    $str2 = "\$string"; /* will output - $string */

    Escaping characters can be very useful, but if you’re using a large number of quotes and other symbols inside a string, things can get confusing. There is an alternative way to specify strings

    Heredoc syntax

    Heredoc syntax is a way to write large sections of text in PHP without the need to worry about escaping quotes. Strings are expressed in this way as follows

    • An initial opening delimiter consisting of three “Less than” symbols (<<<) and a string of your choice - it doesn’t matter what you choose as long as you follow the naming rules for variables (letters, numbers and underscores. The first character cannot be a number
    • On a new line start your string content. This can run onto as many new lines as you like and contain as much content as you require
    • When you wish to terminate a new string, on another new line, place your chosen string followed by a semicolon. This must be the only text on the line (not even comments are allowed) and must not be indented

    Here is an example

    $string = <<<STRINGHERE
    This is a Heredoc syntax string.
    It's very useful
    indeed
    STRINGHERE;

    And this produces

    This is a Heredoc syntax string. It's very useful indeed

    Here is an example of a faulty Heredoc string

    $string = <<<STRINGHERE
    This is a Heredoc syntax string.
    It's very useful
    indeed. But this one is broken
      STRINGHERE; //see the indentation?
    //there should be no comment on the previous line either
    

    Inserting other variables into strings

    PHP includes some powerful methods to combine strings with ease, including the ability to quickly join strings together, and the ability to insert other variables into strings.

    Variables can be inserted into strings in one of three ways

    1. Using the dot (.) operator to concatenate strings and variables. Take the following code

      $a = "This is ";
      $b = "an example of ";
      $c = $a.$b."the dot operator";
      echo $c;

      this produces

      This is an example of the dot operator
    2. By placing the variable directly into the sentence

      $a = "This is ";
      $b = "an example of ";
      $c = "$a$b variable/string insertion";

      This example will only work when using double quotes or Heredoc syntax, strings defined using single quotes do not possess this functionality.

      In this example, we have placed the variable names $a and $b directly into the string. This is a quick and easy way of printing variable names into strings, but you must bear in mind…

      You must make sure to have a space after a variable name and any following text
      For more complex variables such as arrays (outlined later), their more complex syntax requires that you surround them in braces e.g.

      $array = array();
      $array["var"] = "This is an array ";
      $string = "{$array["var"]} inserted into a string";
      echo $string;

      Giving us

      This is an array inserted into a string
    3. When using the echo statement only, variables can be joined together by placing commas between them. This is actually a slightly faster way of printing multiple variables than with the dot operator, but the difference is negligible except for when performing millions of these operations

      $a = "An example of ";
      $b = "joining variables ";
      echo $a,$b,"together with commas";

      Giving us

      An example of joining variables together with commas

      Note that the following code is invalid, since this method only works with echo

      $a = "An example of ";
      $b = "joining variables ";
      print_r ($a,$b,"together with commas"); //invalid
      $c = $a,$b,"together with commas"; //invalid

    Operations on variables

    Now that we know how to assign values to variables, let’s move on to more interesting things, namely making those values work for us in expressions and calculations. PHP makes use of the standard mathematical operators, addition (+), subtraction (-), multiplication (*) and division (/) inside expressions, or calculations to assign values to variables based on the result.

    Expressions using operations are written just like you’d write them down on paper, with two values or expressions either side of each operator, and in the case of an expression using more than one operator, precedence is decided by either using brackets, or through the rules of precedence associated with mathematical operators

    $a = 3+5; //$a is assigned the value 8
    $b = $a-7; //$b becomes 1, since $a represents 8 here
    $c = 6+4*5 //$c becomes 26 (* takes precedence, see paragraph below)
    $d = 5/3 //$d becomes 1.6667, a floating point value

    In line 3 here, we see the rules of operator precedence at work. Multiplication has a stronger precedence than addition, so the expression “4*5″ is evaluated first, to produce 20. The equivalent expression becomes 6+20. If we wanted to have things otherwise, we can use brackets to force precedence to our liking.

    $c = (6+4)*5 //$c becomes 50

    the rules of precedence state that * and / have stronger precedence than + or -, although we can run into more complex situations depending on how we choose to frame our expressions, even when we’re only using one operator

    $a = 3 - 4 - 5; //equals -6
    $b = 3 - (4 - 5); //equals  4

    The full range of operator precendece (which includes logical operators and more) is outside the scope of this tutorial, but it’s something to be constantly vigilant for when writing expressions, to ensure that your values come out the way you’d expect;

    Printing variables to screen

    In an earlier tutorial, I showed you how to output short lines of text to screen using the “echo” statement. The same can be done with variables

    A useful function to keep in mind is var_dump(), which can be used to display useful information about a variable

    $c = "Hello world";
    var_dump($c);
    $c = 5/3;
    var_dump($c);

    Which produces the output

    string(11) "Hello world"
    float(1.6666666666667)

    This tells us that $c initially contains a string with 11 characters. After the division operation, it then contains a floating point value, with the actual value contained in brackets. The function var_dump becomes especially useful when working with arrays

    Constants

    Constants are a special type of variable in PHP which, as their name might suggest, remain constant throughout the execution of an application. Constants can be accessed from anywhere within the codem, regardless of scope, and this combined with their unchanging nature, makes them a good choice for application-wide settings.

    Constants are initialised via the use of the define() function, and can only represent scalar values (i.e. constants cannot represent arrays or other complex data types)

    Here is an example of a constant definition, and usage

    define ("MYCONSTANT", 500);
    echo MYCONSTANT;

    The above code will produce the output

    500

    Constants have to adhere to the same naming conventions as standard variables - an underscore or letter followed by any number of letters, underscores or numbers, and although they can use both uppercase and lowercase lettering, traditionally they are only ever used with upper-case letters, and rarely contain numbers.

    A useful function to use if you wish to recall the value of a constant dynamically (i.e. you need to retrieve a value based on the contents of a variable at runtime) is the constant() function. Here is an example of its usage

    $name = "MYCONSTANT";
    define ("MYCONSTANT", 500);
    echo constant($name);

    Again, this will output

    500

    Referencing variables by Address

    There are two ways to retrieve the value of a variable, they are called by value and by reference. If you imagine a variable as a box containing a particular number, or a particular string, then the way we’ve been accessing this box so far is by looking at what the box contains, and making a new copy of the box every time we wish to assign the value to a new variable.

    Take the following code

    $a = 10;
    $b = $a;
    $a = 20;
    echo "b = ",$b;

    This will produce the fairly obvious output

    b = 10

    Lets look a little deeper into what’s actually happening here though. In line 2 of the above code, we’re assigning the variable $b to be equal to the value held in the variable $a. In line 4, we print this value. Even though the value of $a has changed in line 3, this doesn’t affect the value held in $b, since we’ve already told PHP to assign $b the value of 10. Now, let’s make a little adjustment..

    $a = 10;
    $b = &$a; //so, $b = 10 again, right?
    $a = 20;
    echo "b = ",$b; //nope! $b = 20

    The only change here is an adjustment to the assignment expression in line 2. There is now a new symbol preceding $a, an ampersand. In PHP, this is used to say that, instead of using the value of $a, we are using the location of $a instead. Here, the important thing to consider is that $b is not assigned to the value of $a but instead to whatever $a contains at any given point of time.

    Effectively, we have not created a new copy of a variable, but have simply assigned $b to equal whatever $a equals. And so, the output of the above code will be

    b = 20

    The process is outlined in the following diagram

    Referencing by value or by address

    • 1 : We store the value held in $a within the variable $b
    • 2 : We store a reference to $a within the variable $b. The value of $b will change when the value of $a changes

    Variable Variables

    Variable variables aren’t quite as bewlidering as their name might suggest. Put simply, they are a way of changing the name of variables during program execution, so that multiple values can be accessed through only one line of code. Variable variables are used by preceding the variable name with another dollar sign ($). This new variable then takes, as its name, whatever the value of the original variable way. To make things clearer, here is an example

    $bob = "Hi, my name is Bob";
    $name = "bob";
    echo $$name;

    Which gives us

    Hi, my name is Bob

    Here, on lines 1 and 2, we’re creating two variables, $name and $bob. On line 3, we’re using the “variable variable” $$name, which, in this example, will evaluate to the variable $bob (since $name=”bob”)

    Variable variables can be very useful when you have a large number of variables and wish to dynamically modify them without the hassle of typing in each individually. It’s perhaps a little more complex than the beginner/intermediate scope of this tutorial, but later on, once you’ve mastered arrays and loops, you’ll begin to see how these can be of use

    Predefined Variables in PHP

    PHP provides a number of predefined variables for use in scripts which can be used to gain access to a range of information about the server and filesystem, as well as information about the visitor. For example, the variable $_SERVER contains information about the visitor’s browser and operating system (although nothing which will dramatically impact upon privacy)

    echo $_SERVER['HTTP_USER_AGENT'];

    Will output

    Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1

    Which informs you that I’m using an operating system identifying itself as “Windows NT 6.0″ (actually Vista, but that’s how it reports itself) as well as using the latest version of the Firefox browser.

    Other useful information can be gained through the $_SESSION variable, which provides secure information about the current user, and can be used to manage secure login systems and $_COOKIE, which allows you to track user activity between website visits. If you’ve ever ticked a box on a login screen which asks you “Do you want this site to remember you?”, then that will most likely be using the $_COOKIE variable.

    Also available are user submitted values through the $_GET and $_POST variables, which are essential for processing forms and other information passed from the user to the server. You’ve most likely used forms to submit this sort of information yourself and not even been aware of it - when entering your email address into websites, logging in to secure areas or buying items online and entering your personal details.

    A later tutorial will cover everything you need to know about the $_GET and $_POST variables to construct your own interactive web application

    discuss this topic to forum

    relation tutorial

    No information

    Category

      Ad Management (6)
      Calendars (3)
      Chat Systems (8)
      Content Management (41)
      Cookies and Sessions (12)
      Counters (15)
      Database Related (34)
      Date and Time (15)
      Development (22)
      Discussion Boards (8)
      E Commerce (8)
      Email Systems (14)
      Error Handling (8)
      File Manipulation (36)
      Flash and PHP (6)
      Form Processing (22)
      Guestbooks (12)
      Image Manipulation (26)
      Installing PHP (7)
      Introduction to PHP (24)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (53)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot