🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 2
TEC-WEB46-03 · Lesson 2 · 13 clock hours · demo

PHP Fundamentals: Syntax, Variables, Data Types, and Operators

Objective. Students write PHP scripts that correctly declare variables, use all primitive data types, and apply arithmetic, comparison, and logical operators to produce expected output

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

What Is PHP?

PHP (PHP: Hypertext Preprocessor) is a widely used, open-source, server-side scripting language designed primarily for web development. Unlike HTML, which a browser renders directly, PHP code runs on the web server and sends finished HTML to the client. PHP files use the `.php` extension. Every PHP block opens with `<?php` and, when mixed with HTML, closes with `?>`.

PHP Syntax Basics

A PHP statement ends with a semicolon (`;`). Missing semicolons are one of the most common beginner errors and will halt script execution with a parse error. Comments follow the same conventions as many C-style languages:

PHP is case-sensitive for variable names but case-insensitive for built-in function names and keywords.

Variables and Naming Rules

In PHP every variable name starts with a dollar sign (`$`). Variable names must begin with a letter or underscore, followed by letters, digits, or underscores. They may not contain spaces or start with a digit.

```php

$billAmount = 45.00; // valid

$_taxRate = 0.08; // valid

$2fast = 10; // INVALID — starts with a digit

```

PHP is a loosely typed (dynamically typed) language: you do not declare a type when you create a variable. The interpreter determines the type from the value you assign, and that type can change during execution.

Primitive Data Types

PHP has four scalar (primitive) data types:

| Type | Description | Example literal |

|------|-------------|----------------|

| `int` | Whole numbers, positive or negative | `42`, `-7` |

| `float` | Numbers with a decimal point (also called `double`) | `3.14`, `-0.5` |

| `string` | Text enclosed in single or double quotes | `'hello'`, `"world"` |

| `bool` | Logical true or false | `true`, `false` |

Two additional types you will encounter are `null` (no value) and arrays (covered in a later lesson).

Use `gettype($var)` or `var_dump($var)` to inspect a variable's current type and value — invaluable when debugging.

Type Juggling

Type juggling is PHP's automatic conversion of a value from one type to another based on context. This is a powerful feature but also a common source of bugs.

```php

$a = "5"; // string

$b = 3; // int

$c = $a + $b; // PHP converts "5" to int 5; $c === 8 (int)

```

When a string that begins with a non-numeric character is added to a number, PHP converts it to `0`.

```php

$x = "hello" + 10; // $x === 10

```

Because type juggling can produce surprising results, always use strict comparison operators (see below) when the type matters.

Arithmetic Operators

| Operator | Meaning | Example | Result |

|----------|---------|---------|--------|

| `+` | Addition | `5 + 3` | `8` |

| `-` | Subtraction | `5 - 3` | `2` |

| `` | Multiplication | `5 3` | `15` |

| `/` | Division | `7 / 2` | `3.5` |

| `%` | Modulus (remainder) | `7 % 2` | `1` |

| `` | Exponentiation | `2 3` | `8` |

Integer division that produces a non-whole result automatically returns a `float`.

Comparison Operators

Comparison operators return a `bool`.

Best practice: prefer `===` and `!==` unless you specifically need loose comparison. Loose equality between `0` and `"foo"` evaluated to `true` in older PHP versions, a notorious source of security bugs.

Logical Operators

| Operator | Meaning | Example |

|----------|---------|--------|

| `&&` or `and` | Both true | `$a && $b` |

| `\|\|` or `or` | At least one true | `$a \|\| $b` |

| `!` | Not | `!$a` |

Note that `&&` has higher precedence than `and`; prefer `&&` and `||` in most expressions to avoid precedence surprises.

Reading from the URL Query String

The superglobal `$_GET` array holds values passed through the URL query string. For example, a request to `calc.php?bill=50&tip=18` makes `$_GET['bill']` equal to the string `'50'` and `$_GET['tip']` equal to `'18'`. Always cast or validate these values before arithmetic:

```php

$bill = (float) $_GET['bill'];

$tip = (float) $_GET['tip'];

```

Safety and Best Practices

Web programming does not involve physical electrical hazards the way hardware work does, but it has its own safety concerns:

These habits begin on day one — they are far easier to build than to retrofit.

Key terms8

Type jugglingPHP's automatic conversion of a value from one data type to another based on the context of an operation, which can produce unexpected results if not anticipated.
Scalar typeA single-value data type in PHP: int, float, string, or bool, as opposed to compound types such as arrays or objects.
Loose comparison (==)A comparison that checks whether two values are equal after type juggling, without requiring both operands to be the same type.
Strict comparison (===)A comparison that returns true only when two values are equal in both value and data type, with no type conversion applied.
SuperglobalA built-in PHP associative array that is available in all scopes without being declared, such as $_GET, $_POST, and $_SERVER.
Modulus operator (%)An arithmetic operator that returns the integer remainder after dividing the left operand by the right operand; for example, 7 % 3 returns 1.
var_dump()A PHP built-in function that outputs the data type and value of one or more variables, used primarily for debugging.
CastAn explicit instruction to convert a value to a specific type, written as the target type in parentheses before the value, such as (float) or (int).

Worked examples4

1. A user visits tip.php?bill=85.50&tip=20. Calculate the tip amount and the total bill.
  1. Cast the query string values to float: $bill = (float)'85.50' = 85.50; $tipPct = (float)'20' = 20.0
  2. Convert the percentage to a decimal multiplier: $rate = $tipPct / 100 = 20.0 / 100 = 0.20
  3. Calculate the tip amount: $tipAmount = $bill * $rate = 85.50 * 0.20 = 17.10
  4. Calculate the total: $total = $bill + $tipAmount = 85.50 + 17.10 = 102.60
Answer: Tip amount = $17.10; Total = $102.60
2. A user visits tip.php?bill=120.00&tip=0 (zero tip). What does the script produce?
  1. Cast values: $bill = 120.00; $tipPct = 0.0
  2. Calculate rate: $rate = 0.0 / 100 = 0.0
  3. Calculate tip amount: $tipAmount = 120.00 * 0.0 = 0.00
  4. Calculate total: $total = 120.00 + 0.00 = 120.00
Answer: Tip amount = $0.00; Total = $120.00 — the edge case of a zero tip produces correct output without division by zero or other errors.
3. Predict the output: $a = '4'; $b = 2; $c = $a ** $b; echo $c;
  1. $a is a string '4'; $b is an int 2
  2. The exponentiation operator ** triggers type juggling: PHP converts '4' to int 4
  3. Calculate: 4 ** 2 = 4 * 4 = 16
  4. echo outputs the value of $c
Answer: 16 — PHP type-juggles the string '4' to integer 4 before performing exponentiation.
4. A bill is $47.33 and the tip is 18%. Show the step-by-step arithmetic and round the tip to two decimal places using PHP's round() function.
  1. $bill = 47.33; $tipPct = 18.0
  2. Rate: $rate = 18.0 / 100 = 0.18
  3. Raw tip: 47.33 * 0.18 = 8.5194
  4. Rounded tip: round(8.5194, 2) = 8.52
  5. Total: 47.33 + 8.52 = 55.85
Answer: Tip amount = $8.52; Total = $55.85

The math in this lesson1

Learners code a tip calculator: 20% of $85.50 = $17.10 for a $102.60 total.
7.RP.3
Brush up in the math halls at newSchoolWorks.com:
In class: Instructor live-codes a PHP script showing type juggling; students follow along in their own editor, modify values, and predict output before running — results are discussed as a class · Students complete a structured drill: 20 short PHP snippets with deliberate type or operator errors; they identify and fix each error, noting the type of mistake in a log · Pair programming exercise: partners build a tip-calculator PHP page that accepts a bill amount and tip percentage via URL query string and outputs the tip amount and total, using only PHP fundamentals covered so far
Materials: PHP manual (php.net/manual), VS Code with PHP Intelephense extension, local Apache + PHP environment, instructor-prepared error-drill worksheet
Check: Tip-calculator page produces correct output for at least five test cases including edge cases (zero tip, decimal amounts); code review confirms proper variable naming and operator use — pass requires all five test cases to produce correct output

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA ITF+ — Software Development Concepts
1. Which of the following is a valid PHP variable name?
CompTIA ITF+ — Software Development Concepts
2. A PHP script contains: $x = '10'; $y = 5; $z = $x - $y; What is the value and type of $z?
CompTIA ITF+ — Software Development Concepts
3. What is the result of the expression 17 % 5 in PHP?
CompTIA ITF+ — Software Development Concepts
4. Why is the strict comparison operator === preferred over == when checking whether a form field is empty?
CompTIA ITF+ — IT Security Concepts
5. A developer reads a tip percentage from $_GET['tip'] and uses it directly in multiplication without casting. Which security or correctness risk does this introduce?
CompTIA ITF+ — Software Development Concepts
6. Which PHP function is most useful for inspecting both the data type and current value of a variable during debugging?
CompTIA Linux+ — Linux Troubleshooting and Diagnostics
7. In a Linux-based Apache environment, a student edits a PHP file and saves it, but the browser still shows the old output. Which of the following is the most likely explanation?
PCEP Python — (comparative: understanding typed casting concepts applicable to interpreted languages)
8. Which of the following code lines correctly casts a $_GET value to a float before using it in arithmetic?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.