A Basic Guide to PHP Variables By Examples (original) (raw)

Skip to content

Summary: in this tutorial, you will learn how to use PHP variables to store data in programs.

Defining a variable #

A variable stores a value of any type, e.g., a string, a number, an array, or an object.

A variable has a name and is associated with a value. To define a variable, you use the following syntax:

$variable_name = value;Code language: PHP (php)

When defining a variable, you need to follow these rules:

PHP variables are case-sensitive. It means that $message and $Message variables are entirely different.

The following example defines a variable called $title:

<?php $title = "PHP is awesome!";Code language: HTML, XML (xml)

Try it

To display the values of variables on a webpage, you’ll use the echo construct. For example:

`

PHP Variables

`Code language: PHP (php)

Try it

If you open the page, you’ll see the following message:

PHP is awesome!

Another shorter way to show the value of a variable on a page is to use the following syntax:

<?= $variable_name ?>Code language: PHP (php)

For example, the following shows the value of the $title variable in the heading:

`

PHP Variables
<h1><?= $title; ?></h1>
`Code language: PHP (php)

Try it

Mixing PHP code with HTML will make the code unmaintainable, especially when the application grows. To avoid this, you can separate the code into separate files. For example:

The following shows the contents of the index.view.php file:

`

PHP Variables

`Code language: PHP (php)

The following shows the contents of the index.php file:

`<?php

$title = 'PHP is awesome!'; require 'index.view.php';`Code language: PHP (php)

If you open the index.php file on the web browser, you’ll see the same output.

This separates the code responsible for logic from the code responsible for displaying the file. In programming, this is called the separation of concerns (SoC).

Summary #

Did you find this tutorial useful?