Magyar zászlóMagyar

Practice 7b - PHP Basics

2025-04-03 5 min read GitHub

Introduction

Everything we have built so far runs in the browser — JavaScript, the DOM, Canvas, fetch. The browser downloads the files your server sends and executes them locally.

PHP is different. PHP runs on the server before the response is sent. When a browser requests a .php file, the server executes the PHP code, and the output (usually HTML) is what the browser receives and displays. The browser never sees the PHP source.

This session covers the PHP fundamentals: variables, output, strings, arrays, and loops — compared against what you already know from JavaScript.


Installing PHP

We will use PHP’s built-in development server (php -S). No XAMPP, WAMP, or any other stack is needed.

macOS

macOS ships with an older PHP, but it is usually sufficient. Check first:

php -v

If you need a newer version, install it with Homebrew:

brew install php

After installation, open a new terminal tab and confirm with php -v again.

Windows

  1. Go to windows.php.net/download
  2. Download the latest VS16 x64 Non Thread Safe ZIP under the current stable release
  3. Extract the ZIP to a permanent folder, e.g. C:\php
  4. Add C:\php to your PATH environment variable:
    • Search “Edit the system environment variables” → Environment Variables → select Path under “User variables” → Edit → New → C:\php
  5. Open a new terminal and confirm:
php -v

Linux (Debian / Ubuntu)

sudo apt update
sudo apt install php
php -v

Running the built-in server

Navigate to the folder that contains your .php file and start the server:

php -S localhost:8080

Then open http://localhost:8080/1.php in the browser. The terminal will log each request.

💡

Stop the server with Ctrl + C in the terminal. The server automatically reloads changes on each request — no restart needed.


PHP file structure

Every PHP file starts with the opening tag <?php. The closing tag ?> is optional in files that contain only PHP (and is usually omitted). In files that mix PHP and HTML you use opening and closing tags to switch between the two modes.

<?php
// all PHP code goes here
echo "Hello World!";
?>

The output of echo is sent as raw text. In a file served over HTTP, that means HTML — so you write HTML tags inside your strings:

echo "Hello World!<br />";

1. Output — echo and print

PHP has two basic output functions. Both send a value to the response:

$x = 5;
echo $x;       // outputs: 5
echo($x);      // parentheses are optional

print $x;      // same output
print($x);     // same

The practical difference: print always returns 1 (so it can be used inside expressions), while echo is marginally faster and can take a comma-separated list. In practice, echo is the one you will see and use almost always.

ℹ️

In JavaScript you log values with console.log(). In PHP the equivalent for debugging is var_dump($x) or print_r($x). They work differently for arrays and objects, which we cover below.


2. Variables

In PHP every variable name starts with $. There is no let, const, or var:

$x = 5;
$name = "Alice";
$isReady = true;
JavaScriptPHP
let x = 5$x = 5;
const PI = 3.14define('PI', 3.14); or just $pi = 3.14;
typeof xgettype($x)

PHP is dynamically typed like JavaScript — you do not declare a type; it is inferred from the assigned value.


3. Strings and concatenation

JavaScript uses + to join strings. PHP uses . (a dot):

$y = 10;
echo "The value of y is " . $y . ". ok<br>";

The JavaScript equivalent:

console.log(`The value of y is ${y}. ok`);
// or:
console.log("The value of y is " + y + ". ok");

Double quotes vs single quotes

In double-quoted strings, variable names are expanded:

$name = "Alice";
echo "Hello $name";     // outputs: Hello Alice
echo 'Hello $name';     // outputs: Hello $name  (literal — no interpolation)

Single-quoted strings are treated as raw text — no variable interpolation, no escape sequences (except \\ and \'). They are slightly faster and useful when you want the $ to appear literally.


4. Arrays

PHP arrays are ordered lists, just like JavaScript arrays:

$a = [1, 2, 3, 4, 5, 6];
echo $a[0];              // 1
echo count($a);          // 6  (JavaScript: a.length)
JavaScriptPHP
[1, 2, 3][1, 2, 3]
a.lengthcount($a)
a[0]$a[0]

Inspecting arrays — print_r

print_r prints a human-readable representation of any value, including nested arrays:

echo "<pre>";
print_r($a);
echo "</pre>";

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    ...
)

The <pre> tags preserve whitespace so the indented output is readable in the browser.

Associative arrays

PHP arrays can also use string keys. These are called associative arrays and work like JavaScript objects:

$car = [
    "year"   => 2026,
    "model"  => "Tesla",
    "broken" => false,
];

echo $car["model"];   // Tesla
JavaScriptPHP
{ year: 2026, model: "Tesla" }["year" => 2026, "model" => "Tesla"]
car.model or car["model"]$car["model"]

5. Loops

for loop

Identical concept to JavaScript, different syntax for the variable:

for ($i = 0; $i < count($a); $i++) {
    echo "Element " . $i . ": " . $a[$i] . "<br />";
}

JavaScript equivalent:

for (let i = 0; i < a.length; i++) {
    console.log(`Element ${i}: ${a[i]}`);
}

foreach — iterating values

foreach ($a as $item) {
    echo $item . "<br />";
}

JavaScript equivalent:

for (const item of a) {
    console.log(item);
}

foreach — iterating index and value

foreach ($a as $index => $value) {
    echo "Element " . $index . ": " . $value . "<br />";
}

JavaScript equivalent:

a.forEach((value, index) => {
    console.log(`Element ${index}: ${value}`);
});
// or: for (const [index, value] of a.entries()) { ... }

6. Useful string/array functions

PHP has counterparts for common JavaScript array and string methods:

implode — equivalent to Array.join()

echo implode(", ", $a);   // "1, 2, 3, 4, 5, 6"

JavaScript:

a.join(", ");   // "1,2,3,4,5,6"

explode — equivalent to String.split()

$parts = explode(", ", "1, 2, 3, 4, 5, 6");

echo "<pre>";
print_r($parts);
echo "</pre>";

JavaScript:

"1, 2, 3, 4, 5, 6".split(", ");  // ["1", "2", "3", "4", "5", "6"]

Complete 1.php

<?php

echo "Hello World!<br />";

$x = 5;
echo $x;
echo "<br />";
echo($x);

echo "<br />";
print $x;
print($x . "<br />");

$y = 10;
echo "The value of y " . $y . ". ok <br>";
echo 'I am a <strong>string</strong><br /><br />';

// Arrays
$a = [1, 2, 3, 4, 5, 6];
echo "<pre>";
print_r($a);
echo "</pre>";
echo $a[0] . "<br />";

// for loop
for ($i = 0; $i < count($a); $i++) {
    echo "This is the " . $i . "-th element: " . $a[$i] . "<br />";
}

// foreach — values only
foreach ($a as $item) {
    echo "This is: " . $item . "<br />";
}

// foreach — index and value
foreach ($a as $index => $value) {
    echo "This is the " . $index . "-th element: " . $value . "<br />";
}

// Associative array
$car = [
    "year"   => 2026,
    "model"  => "Tesla",
    "broken" => false,
];

// implode / explode
echo implode(", ", $a);

echo "<pre>";
print_r(explode(", ", "1, 2, 3, 4, 5, 6"));
echo "</pre>";

?>

PHP vs JavaScript — quick reference

ConceptJavaScriptPHP
Variable declarationlet x = 5$x = 5;
Outputconsole.log(x)echo $x;
String concatenation"Hello " + name"Hello " . $name
String interpolation`Hello ${name}`"Hello $name"
Array lengtha.lengthcount($a)
Array inspectionconsole.log(a)print_r($a)
Loop over arrayfor...of, forEachforeach ($a as $v)
Loop with indexa.forEach((v, i) => ...)foreach ($a as $i => $v)
Join arraya.join(", ")implode(", ", $a)
Split strings.split(", ")explode(", ", $s)
Key-value object{ key: value }["key" => value]
Object propertyobj.key or obj["key"]$obj["key"]

Summary

ConceptPHP
Variable$name = value;
Outputecho "..."
String concatenation. (dot)
Double-quoted stringInterpolates $variables
Single-quoted stringLiteral — no interpolation
Indexed array[1, 2, 3]
Associative array["key" => value]
Array lengthcount($a)
Debug printprint_r($a)
for loopfor ($i = 0; $i < count($a); $i++)
foreach (values)foreach ($a as $item)
foreach (index + value)foreach ($a as $index => $value)
Join array to stringimplode(separator, $a)
Split string to arrayexplode(separator, $s)
Built-in dev serverphp -S localhost:8080