PHP Variables 🎯

beginner
14 min

PHP Variables 🎯

Welcome to our PHP Variables tutorial! In this lesson, we'll learn about an essential building block of any programming language - variables. By the end of this tutorial, you'll have a solid understanding of how to create, use, and manage variables in PHP. Let's get started! πŸŽ‰

What are Variables? πŸ“

In simple terms, a variable is a container that stores data. In PHP, you can create variables to store different types of data such as numbers, strings, and even other variables.

php
$myNumber = 10; $myString = "Hello, World!"; $myVariable = $myNumber;

In the above example, we have created three variables: $myNumber, $myString, and $myVariable.

πŸ’‘ Pro Tip:

  • Variable names in PHP should always start with a $ symbol.
  • Variable names are case-sensitive. For example, $myNumber and $mynumber are considered different variables.

Variable Types πŸ“

There are two main types of variables in PHP:

  1. Scalar Variables: These variables can store a single value such as integers, floating-point numbers, strings, or booleans.
php
$myInteger = 123; $myFloat = 123.456; $myString = "This is a string."; $myBoolean = true;
  1. Compound Variables: These variables can store multiple values as an array or object. We'll explore arrays in a future tutorial.

Assigning and Changing Variable Values πŸ“

You can assign values to variables and change their values at any point during your PHP script.

php
$myVariable = 5; echo $myVariable; // Output: 5 $myVariable = 10; echo $myVariable; // Output: 10

PHP Variable Naming Rules πŸ“

  1. A PHP variable name can contain letters, digits, and underscores.
  2. The first character of a PHP variable name must be a letter or underscore.
  3. Case sensitivity: $myVariable and $myvariable are considered different variables.
  4. Reserved words and predefined constants cannot be used as variable names.

Using Variables in PHP Code πŸ“

You can use variables in your PHP code to make it more dynamic. Here's an example of a simple PHP script that uses variables to calculate the area of a rectangle.

php
$length = 5; $width = 10; $area = $length * $width; echo "The area of the rectangle is: " . $area;

This script calculates the area of a rectangle with a length of 5 and a width of 10, and outputs "The area of the rectangle is: 50".

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What is the first character allowed in a PHP variable name?


By now, you should have a good understanding of PHP variables and how to create and use them in your code. In the next lesson, we'll dive deeper into PHP data types and explore arrays. Stay tuned! 🌟