Understanding PHP Variables

PHP variables are used to store data that can be used and manipulated throughout your script. Variables in PHP are identified by a $ sign, followed by the variable name.

Creating Variables in PHP

To create a variable in PHP, simply write:

<?php
    $name = "Alice"; // String variable
    $age = 25; // Integer variable
    $isStudent = true; // Boolean variable
    ?>

In the example above:

  • $name stores a string value "Alice".
  • $age stores an integer value 25.
  • $isStudent stores a boolean value true.

Outputting Variables

You can output the value of a variable using echo or print:

<?php
    $name = "Alice";
    echo "Hello, my name is $name.";
    ?>

Output:

Hello, my name is Alice.

Variable Naming Rules

Here are some rules for naming variables in PHP:

  • Variable names must start with a letter or an underscore (_).
  • Variable names cannot start with a number.
  • Variable names can only contain letters, numbers, and underscores.
  • Variable names are case-sensitive ($name and $Name are different).

Concatenating Strings

You can combine variables and strings using concatenation with a dot (.):

<?php
    $name = "Alice";
    $greeting = "Hello, " . $name . "!";
    echo $greeting;
    ?>

Output:

Hello, Alice!

Next Steps

Experiment with different types of variables and operations in PHP. Understanding how variables work is essential for mastering PHP and building dynamic web applications. Now you can learn about if else statements!