PHP 101: Variables (Part 3)

Follow @tristarweb

Hello again, welcome back to our PHP 101 web design tutorials. Today I am going to explain the use of variables, and what they are.

A variable is a method of storing a value throughout a PHP page. A variable can store strings of text, integers (1, 2, 3, 4, etc), or an array (I will explain arrays at a later date). For example, if you wanted to use the string “James is teaching some PHP…” throughout your PHP document, then instead of writing it out every time you could declare it as a variable and use that in your PHP instead. That would look like this:

<?php $james = "James is teaching some PHP..."; ?>

And then wherever you want to use that string of text, you can just use:

<?php echo $james; ?>

Variable Naming Conventions

  • Variables must always start with a dollar sign.
  • In PHP, you simply need to write “$variable =” to initiate it; some languages, like javascript, require you to write “var variable =”, but this is not the case in PHP.
  • Variables are case sensitive, so “$James” is not the same as “$james”.
  • Variables must only contain alphanumeric values, such as a-z, A-Z, 0-9, and _
  • No spaces must be used in a variable name, you should use underscores “$my_variable”, or capitalisation “$myVariable”

Example Variables

The following are all examples of valid variables:

<?php

        $number = 6;
        $anotherNumber = 12;
        $another_number = 8;
        $string = "This is a string!";
        $array = array("value 1", "value 2", "value 3");

?>

Conclusion

I hope this helps you understand what a variable is, and how it works – we will be using variables in more depth as this series goes on, so be sure to stay tuned.

The next post will be about operators in PHP – keep checking back to make sure you don’t miss it, or follow our blog RSS feed.

About James

Hello there, I'm James. I studied Music Technology at university and gained a BA Hons in Music Technology and Innovation. I really enjoyed studio engineering and MaxMSP (a programming language for synthesisers). This inspired me to move into programming.I now specialise in front end development and bespoke Wordpress powered websites.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please wrap all source code with [code][/code] tags.

Follow Tristar on Twitter