Unit 10 ยท Back-End Programming

10.1.4PHP language essentials

PHP
<?php
// Variables start with $. Types are decided automatically.
$name = 'Nimal';          // string
$age = 21;                // integer
$price = 49.99;           // float
$active = true;           // boolean
$colors = ['red', 'green', 'blue'];                  // indexed array
$student = ['name' => 'Kamal', 'age' => 20];         // associative array

echo 'Hello ' . $name . '<br>';        // . joins strings
echo "Age: $age";                      // double quotes expand variables
echo $colors[1];                       // green
echo $student['name'];                 // Kamal
$colors[] = 'yellow';                  // append
echo count($colors);                   // 4

// Control structures
if ($age >= 18) { echo 'Adult'; } elseif ($age >= 13) { echo 'Teen'; } else { echo 'Child'; }

for ($i = 1; $i <= 5; $i++) { echo $i; }
foreach ($colors as $c) { echo $c . ' '; }
foreach ($student as $key => $value) { echo $key . '=' . $value . ' '; }
while ($age < 25) { $age++; }

switch ($name) {
    case 'Nimal': echo 'Hi Nimal'; break;
    default: echo 'Who?';
}

// Functions
function total(float $price, int $qty = 1): float {
    return $price * $qty;
}
echo total(49.99, 3);

// Useful built-ins
strlen($name); strtoupper($name); trim(' x '); str_replace('a', 'b', $name);
isset($x); empty($x); date('Y-m-d'); number_format(1234.5, 2); round(3.456, 2); rand(1, 6);

// Reuse code from other files
include 'header.php';          // warning if missing
require 'config.php';          // fatal error if missing
require_once 'db.php';         // load only once
?>

Key differences from JavaScript: $ before variables; . joins strings (not +); => in associative arrays; foreach for lists; == and === work as in JavaScript (=== also checks the type). PHP code lives between <?php ... ?>; omit the closing tag in files that contain only PHP.

Mixing PHP and HTML:

PHP
<?php $items = ['Pen', 'Book', 'Bag']; ?>
<ul>
  <?php foreach ($items as $item): ?>
    <li><?= htmlspecialchars($item) ?></li>   <!-- <?= is short for echo -->
  <?php endforeach; ?>
</ul>

Always escape output with htmlspecialchars() when printing user data. This prevents XSS (cross-site scripting), where an attacker's <script> runs in other users' browsers.

Try it: Write multiplication.php that prints a table for any number given by ?n=7 in the URL ($_GET['n']). Write a function grade($marks) returning A, B, C or F and show results for an array of students.