Hello World
<?php
echo "Hello, world!" . PHP_EOL;
Run the script:
php main.php
This writes one line from a PHP script. PHP_EOL keeps the newline portable across environments.
Variables
Variables start with $. Use strict comparisons when the type matters.
$name = "Dan";
$count = 1;
$active = true;
if ($count === 1) {
echo $name;
}
This shows normal PHP variables and a strict comparison, which is the safer choice when type differences matter.
Arrays
PHP arrays can be lists or key-value maps.
$names = ["Ana", "Dan", "Mara"];
$user = [
"id" => 1,
"email" => "[email protected]",
"active" => true,
];
echo $names[0];
echo $user["email"];
PHP arrays can work like lists or maps, so the same structure covers both simple sequences and keyed data.
Conditionals
if ($user["active"]) {
echo "active";
} elseif ($user["id"] === null) {
echo "missing";
} else {
echo "inactive";
}
This is the normal if / elseif / else flow for branching based on the current data.
Loops
Use foreach for arrays. It works with both lists and associative arrays.
foreach ($names as $name) {
echo $name . PHP_EOL;
}
foreach ($user as $key => $value) {
echo $key . ": " . var_export($value, true) . PHP_EOL;
}
These examples show foreach, which is the most practical way to iterate PHP arrays.
Functions
Type parameters and return values where practical.
function greet(string $name): string
{
return "Hello, {$name}!";
}
echo greet("world");
This defines a typed function with a string input and string output, which makes intent clearer and catches mistakes earlier.
Classes
Constructor property promotion keeps simple data objects compact.
class User
{
public function __construct(
public int $id,
public string $email,
public bool $active = true,
) {
}
}
$user = new User(1, "[email protected]");
if ($user->active) {
echo $user->email;
}
This shows a compact data-focused class. Constructor property promotion keeps the class short when it mostly stores values.