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.
PHP Add
function add($param1, $param2) {
return $param1 + $param2;
}
This just adds the two input numbers with the language’s normal arithmetic and returns the sum.
PHP Add Border
function addBorder($picture) {
array_unshift($picture,str_repeat("*",strlen($picture[0])));
foreach($picture as $k=> $v) {
$picture[$k] = "*{$v}*";
}
$picture[] = str_repeat("*", strlen($picture[0]));
return $picture;
}
This builds a new grid with a * border around every side. It adds a full top and bottom row, then wraps each existing row from left and right.
PHP Adjacent Elements Product
function adjacentElementsProduct($inputArray)
{
$max = PHP_INT_MIN;
for ($i = 0, $c = count($inputArray); $i < $c - 1; $i++) {
$max = max($max, $inputArray[$i] * $inputArray[$i + 1]);
}
return $max;
}
This walks through neighboring values, multiplies each pair, and keeps the biggest product it finds.
PHP Almost Magic Square
function almostMagicSquare(array $a): array
{
$rowSum = $colSum = array_fill(0, 3, 0);
$maxSum = 0;
$a = array_chunk($a, 3);
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$rowSum[$i] += $a[$i][$j];
$colSum[$i] += $a[$j][$i];
}
}
foreach ($rowSum as $k => $v) {
$maxSum = max($maxSum, $v);
$maxSum = max($maxSum, $colSum[$k]);
}
for ($i = 0, $j = 0; $i < 3 && $j < 3;) {
$diff = min($maxSum - $rowSum[$i], $maxSum - $colSum[$j]);
$a[$i][$j] += $diff;
$rowSum[$i] += $diff;
$colSum[$j] += $diff;
if ($rowSum[$i] === $maxSum) {
$i++;
}
if ($colSum[$j] === $maxSum) {
$j++;
}
}
return array_merge([], ...$a);
}
This adjusts the matrix toward a matching target sum so the rows and columns line up more like a magic square.
PHP Are Equally Strong
function areEquallyStrong($yourLeft, $yourRight, $friendsLeft, $friendsRight)
{
return max($yourRight, $yourLeft) === max($friendsLeft, $friendsRight)
&& min($yourLeft, $yourRight) === min($friendsRight, $friendsLeft);
}
This compares each person’s strongest and weakest arm. If both pairs match, the result is true.
PHP Array Change
function arrayChange($a)
{
$min = 0;
for ($k = 0, $c = count($a); $k < $c - 1; $k++) {
if ($a[$k] >= $a[$k + 1]) {
$dif = $a[$k] - $a[$k + 1] + 1;
$a[$k + 1] += $dif;
$min += $dif;
}
}
return $min;
}
This moves left to right and bumps values only when needed so the array becomes strictly increasing.
PHP Array Maximal Adjacement Difference
function arrayMaximalAdjacentDifference($a)
{
$dif = 0;
for ($i = 1, $c = count($a); $i < $c - 1; $i++) {
$dif = max($dif, abs($a[$i] - $a[$i - 1]), abs($a[$i] - $a[$i + 1]));
}
return $dif;
}
This checks the gap between each pair of neighbors and returns the largest difference.
PHP Binary Gap
function binaryGap(int $n): int
{
$gap = 0;
$zeroes = explode('1', trim(decbin($n), '0'));
foreach ($zeroes as $zero) {
$len = strlen($zero);
$gap = $len > $gap ? $len : $gap;
}
return $gap;
}
This turns the number into binary, ignores zeroes outside the edges, and finds the longest run of zeroes between 1s.
PHP Bracket
function bracket(string $s): int
{
$stack = [];
foreach (str_split($s) as $v) {
switch ($v) {
case ')':
if (empty($stack) || array_pop($stack) !== '(') {
return 0;
}
break;
case ']':
if (empty($stack) || array_pop($stack) !== '[') {
return 0;
}
break;
case '}':
if (empty($stack) || array_pop($stack) !== '{') {
return 0;
}
break;
default:
if ( ! empty($v)) {
$stack[] = $v;
}
break;
}
}
return empty($stack) ? 1 : 0;
}
This uses a simple stack approach: open brackets go in, matching closing brackets pop them out.