0% complete

PHP Basics · Lesson 1 of 8

Variables

Create variables, assign values, and follow PHP naming rules.

Lesson

A variable stores a value that your program can reuse or change. In PHP, a variable name starts with a dollar sign followed by a letter or underscore; later characters may also include digits. Assign a value with the = assignment operator. PHP determines a variable’s current type from its value, and the same variable can later hold a value of a different type. Prefer clear names and consistent types where that makes code easier to maintain. Variable names are case-sensitive, so $name and $Name are different variables. Names cannot begin with a digit, and spaces are not allowed. Example: $name = "Piyush"; stores a string. echo $name; writes that value to the response. When inserting variable data into HTML, escape it for the correct output context. Further guidance Inspect a value before relying on an implicit conversion. Keep input validation separate from casting, use strict comparisons when type matters, and choose an explicit representation for values such as money or optional data. Try normal, empty, and unexpected inputs so the result is deliberate. Practice task: Create a fresh example for Variables. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Assign and display variables
PHP
$name = "Piyush";
$age = 25;

echo $name;
echo "\n";
echo $age;
Expected output
Piyush
25

Key points

  • Variable names begin with $.
  • Variable names are case-sensitive and cannot start with a number.
  • Escape values when outputting them into HTML.

Check your understanding

Practice

Which character must start a PHP variable name?

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.