Create & name variables in PHP

Every programming language has the concept of variables, and they are used any time you wish to store data, and then reference it somewhere later on in your code.

PHP’s variables always start with a dollar sign.

Let’s create a new variable for a fictitious blog we’ll be creating. We’ll do that by opening up another php tag at the top of our script, then create a $title variable, and set it equal to “My Blog”

Remember that we’ll need to use a semicolon because our script is now not completely PHP, but a mix of HTML and PHP. We’ll also need to close up this PHP bracket to tell PHP that our script is done executing.

<?php
$title = 'My Blog';
?>
<h1><?= $title ?></h1>

Refreshing the page, we’ll see this works as expected.

Note that the name “title’ is completely arbitrary, and can be whatever you want.

Variables cannot start with a number, or contain special or odd non-alphanumeric characters.

<?php
$1title= 'My Blog';
?>
<h1><?= $1title ?></h1>

A good IDE will complain about invalid variables.

If you would like your variable to contain more than one word, for example My Title, you can use either snake_case by making all letters lowercase and words are delimited with underscores.

<?php
$my_title = 'My Blog';
?>
<h1><?= $my_title ?></h1>

Or you can use camelCase, by making the first letter of the first word lowercase, and the first letter of the second word uppercase:

<?php
$myTitle = 'My Blog';
?>
<h1><?= $myTitle ?></h1>

Which format you wish to use is completely up to you! Some prefer snake_case because it’s generally easier to read, while others prefer camelCase because it more closely aligns with how JavaScript variables are named. I personally prefer camelCase, but whichever you choose, just pick a format and stick with it, so you don’t drive your coworkers or others crazy.

For now, let’s just set this back to $title, because this is the most straightforward name at the moment for this variable.

<?php
$title = 'My Blog';
?>
<h1><?= $title ?></h1>


Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock