PHP: Basic Variables

So, you want to write some PHP?  I’m going to go over some basics of PHP in the next few posts.  This first post is going to cover basic variables.

Step #1: You need to define set up your PHP file

PHP is executed out of files that end in ‘.php’ (as you might expect).  You also need to define where, in the file, your PHP code is.  That’s done by prepending your code with ‘<?php’ and appending it with ‘?>’.  Let’s see what that looks like.

<?php
// Your code goes here
?>

Keep in mind, that you are still working inside of an html document, though.  This means that your code, will more typically look like this:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
// Your code goes here
?>
</body>
</html>

The closing ‘?>’ is optional if there are no other HTML tags in the document.  This means that you can write legitimate code that looks like …

<?php
    // Your code goes here

… but you would get a parse error if you write code that looks like

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<?php
// Your code goes here

</body>
</html>

 

Step #2: Variables

PHP variables begin with a ‘$’ and must not have a number symbol directly following the ‘$’.  A variable name can only contain letters, numbers, or underscore.  PHP is a loosely typed language.  This means that you don’t specify a variable type and can change the type by just assigning a different type of value to the variable.  Let’s see what a variable declaration looks like:

<?php
    $firstName = 'Joe';
?>

In the above example, I defined $firstName as a string containing the value ‘Joe’.  You can change that value again like so

<?php
    $firstName = 'Joe';
    $firstName = 1.1;
?>

The variable $firstName is now a float with the value ‘1.1’.

 

Step #3: Output Your Values

PHP has two ways of outputting to the display.  You can use ‘echo’ or ‘print’.  Echo would look like …

<?php
    $firstName = 'Joe';
    echo $firstName;
?>

… while print looks like

<?php
    $firstName = 'Joe';
    print $firstName;
?>

‘Echo’ has a benefit over ‘print’ in that you can feed it a comma-delimited list of values.

<?php
    $firstName = 'Joe';
    $lastName = 'Steinbring';
    echo $firstName, $lastName;
?>

 

You do not necessarily need to use ‘echo’ or ‘print’ to output inside of a PHP file, though.  There is a shortcut for output of values.  Let’s check out a short demonstration.

<?php
    $title = 'My Test';
    $h1 = 'This is my test';
    $p = 'Hi there!';
?>
<!DOCTYPE html>
<html>
<head>
	<title><?= $title ?></title>
</head>
<body>
    <h1><?= $h1 ?></h1>
    <p><?= $p ?></p>
</body>
</html>

You can see how that would be an easier syntax for output of values.

Leave a Reply

Your email address will not be published.