You are on page 1of 3

In PHP, variables are used to store data or values that can be manipulated or referenced within a script.

Variable names in PHP start with the dollar sign ($) followed by the variable name. Here are some key
points about variables in PHP:

1. **Variable Naming Rules**:

- Variable names in PHP are case-sensitive.

- Variable names must start with a letter or underscore (_), followed by letters, numbers, or
underscores.

- Variable names cannot start with a number.

2. **Variable Assignment**:

Variables in PHP are assigned values using the assignment operator (=). For example:

```php

$name = "John";

$age = 25;

```

3. **Data Types**:

PHP supports various data types for variables, including:

- Integer: Whole numbers without decimal points.

- Float (or Double): Numbers with decimal points.

- String: Textual data enclosed within single or double quotes.

- Boolean: Represents true or false.

- Array: Ordered collection of elements.

- Object: Instances of user-defined classes.

- Null: Represents a variable with no value.


4. **Variable Scope**:

- PHP supports different variable scopes, including global, local, static, and superglobal.

- Variables declared outside of functions are considered global and can be accessed from anywhere in
the script.

- Variables declared within a function are local to that function and cannot be accessed outside of it
unless explicitly declared as global or passed as function arguments.

5. **Variable Output**:

Variables can be output directly within double-quoted strings using variable interpolation or
concatenated with strings using the dot (.) operator. For example:

```php

echo "Hello, $name!"; // Output: Hello, John!

echo "Age: " . $age; // Output: Age: 25

```

6. **Variable Manipulation**:

Variables in PHP can be manipulated using various operators, functions, and language constructs. For
example, arithmetic operations, string concatenation, and array manipulation.

Here's a simple example demonstrating variable usage in PHP:

```php

$name = "Alice";

$age = 30;

$isStudent = true;

echo "Name: $name\n";


echo "Age: $age\n";

echo "Is Student: " . ($isStudent ? "Yes" : "No") . "\n";

```

This code declares variables for name, age, and student status and then outputs their values.

You might also like