Codectionary / Developer documentation / PHP

PHP Variables & Strings

PHP variables start with $. Double-quoted strings interpolate variables, while single-quoted strings generally treat their contents literally.

Syntax

$name = "Ada";
echo "Hello, $name";

Breaking down the syntax

$name
A variable identifier.
=
Assignment.
echo
Writes one or more strings.

How it works

PHP variables start with $. A variable can hold text, numbers or other values, and echo writes output.

Input or value

Obtain the data.

Variable

Assign it to a meaningful name.

Output

Format the result for its destination.

Examples

A small working example

Follow the values through this example, then change one input.

<?php
$name = "Ada";
$lessons = 3;
echo "$name completed $lessons lessons\n";
  1. Variables begin with $.
  2. The double-quoted string interpolates their values.
  3. echo writes the resulting text.

Printing a greeting

A small, runnable example of this syntax.

<?php
$name = "Ada";
$count = 3;
echo "$name has $count messages.";
?>

Best practices

  • Use descriptive variable names and keep presentation templates separate from application logic as a project grows.
  • Keep examples small while learning, then combine the idea with a real project.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

When should I use this?

Name values in server-side request handling or command-line scripts.

Common mistakes

A common trap

Variable names are case-sensitive.

Incorrect

$name = "Ada";
echo $Name;

Corrected

$name = "Ada";
echo $name;

Compare approaches

  • Single-quoted string: Mostly literal text.
  • Double-quoted string: Variable interpolation and escape sequences.

Explore deeper

Output depends on context

When inserting untrusted text into HTML, encode it for the HTML context. Plain echo does not automatically make user input safe for a web page.

Specifications & further reading