Basics
- Code is written inside
<?php ?>tags. echooutputs one or more strings separated by commas, concatenated with dots.PHP_EOLis the newline constant.printoutputs only one string and always returns 1.- Ternary operator
?:e.g.,1+2==3 ? 4 : 5returns 4 if true, else 5. - Null coalescing operator
??:$a ?? "b"returns$aif defined and not null, otherwise"b". - Spaceship operator
<=>:$c = $a <=> $b; returns 1 if $a > $b, 0 if equal, -1 if $a < $b. Works with strings, comparing ASCII characters from left to right. isset($a)returns true if variable is declared and not null.is_null($a)returns true if value is null; throws notice if undefined.empty($a)returns true for 0, false, null, empty array, empty string, and undefined (though not recommended for checking undefined variables).
Loops
switchloops requirebreakto exit.
// Without break, execution continues through all subsequent cases after first match.
switch ($favfruit) {
case "apple":
echo "Your favorite fruit is apple!";
case "banana":
echo "Your favorite fruit is banana!";
case "orange":
echo "Your favorite fruit is orange!";
default:
echo "Your favorite fruit is neither apple, banana, or orange!";
}
continueskips the rest of the current loop iteration and proceeds to the next one. It does not exit the loop.breakexits the current loop or switch. With an optional numeric argument, it breaks out of that many nested structures. Default is 1.
for($i = 1; $i <= 10; $i++){
for($j = 1; $j <= 10; $j++){
$m = $i * $i + $j * $j;
echo "$m \n<br/>";
if($m < 90 || $m > 190) {
break 2; // Breaks out of both loops
}
}
}
Arrays
PHP arrays are similar to objects in other languages; you can specify keys for each element. If no key is specified, numeric indices (0,1,2...) are assigned by default. Common functions: count() returns array length, print_r() prints the array, foreach iterates.
$a = ["name" => "tom", "age" => "12", "sex" => "man"];
$b = [1,2,3];
$b = [
[1,2,3],
["a" => 11, "b" => 22, "c" => 23],
];
print_r($a);
print_r($b);
echo count($a);
echo $a['name'];
echo $b[1]["a"];
// Iterate
foreach($a as $key => $value){
echo PHP_EOL . $key . $value;
}
// Append (default numeric key)
$b[] = $c;
Array Operations
- Addition (
+): Merges two arrays. For duplicate keys, the element from the left array is kept; unique keys are appended. array_merge($a, $b): Similar to addition but for duplicate keys, the right array's value overrides the left's.- Equality:
==returns true if both arrays have the same key/value pairs, ignoring order.===requires same key/value pairs, same order, and same types.
Real-World Example with Arrays in Websites
<?php
$contentArr = [
[
"content" => "Here is your blog content. You can write your own web pages using HTML and CSS.",
"createDay" => "2023.09.25"
],
[
"content" => "Personal Introduction",
"createDay" => "2023.09.23"
],
[
"content" => "Article List",
"createDay" => "2023.09.22"
],
[
"content" => "Contact Info",
"createDay" => "2023.09.21"
],
[
"content" => "Here is",
"createDay" => "2023.09.20"
],
];
$content = "Here is your blog content. You can write your own web pages using HTML and CSS.";
$creatDay = "2023.09.25";
?>
<div class="container">
<h1 class="title">Welcome to My Blog</h1>
<!-- Iterate array and output to HTML -->
<!-- foreach can be split with PHP tags around HTML -->
<?php foreach($contentArr as $key => $value): ?>
<div class="text-area">
<span class="number"><?php echo ($key+1) ?></span>
<span class="create-day"><?php echo $value["createDay"] ?></span>
<?php echo $value["content"] ?>
</div>
<?php endforeach; ?>
<!-- Using heredoc syntax -->
<?php
foreach($contentArr as $value){
echo <<<EOF
<div class="text-area">
<span class="create-day">{$value["createDay"]}</span>
{$value["content"]}
</div>
EOF;
}
?>
<div class="text-area">
<span class="create-day"><?php echo $creatDay ?></span>
<?php echo $content ?>
</div>
</div>
String Functions
strlen()- string length (1 for English char, 3 for Chinese char usually)strpos($str, "xxx")- find first occurrence position, returns false if not foundstripos()- case-insensitive versionstrrpos()- find last occurrence positionstrripos()- case-insensitive last occurrenceexplode(",", $str)- split string into array by delimiterimplode(",", $str)- join array elements into string with delimiterstrtoupper()- convert to uppercasestrtolower()- convert to lowercasestr_replace($search, $replace, $str)- replace occurrencestrim()- strip whitespace from both endssubstr()- extract substring- More functions: refer to w3schools or php.net.
Heredoc Syntax
When outputting long strings with multiple concatenations, heredoc simplifies. Start with <<<EOF, end with EOF; on its own line (no indentation, semicolon at end). Inside heredoc, variables and array elements must be enclosed in braces.
foreach($navbarArr as $value){
$x = $value["title"];
echo <<<EOF
{$value["title"]}
EOF;
}
Functions
date('Y-m-d h-m-s')- date/time formatting (Y=year with century, y=two-digit year)- Defining functions:
function name() {}
function name($a) {}
function name(int $a) {}
// Strict types declaration
declare(strict_types=1);
function name(int $a) {}
static variables
Static variables retain their value after function execution.
function run(){
static $a = 0;
$a++;
return $a;
}
// Each call increments $a; without static, it always returns 1.
unset($a) - delete variable
isset($a) - check if variable exists
global - define global variable (even inside function)
$GLOBALS - superglobal array: $GLOBALS['name'] = "xxx"; makes it global.
Constants
- Constants are named without
$, case-sensitive (convention uppercase), global by default. - Once defined, cannot be changed or undefined.
constcannot be used in conditional statements; can be used inside classes.define()cannot be used for class member variables, but can be used inside class methods.get_defined_constants()retrieves all constants.
define("NAME", "This is a constant");
const NAME2 = "Another constant";
File Inclusion
requireinclude- syntax:include "./xx.php";
Classes
- Access members and methods with
->. - Access control:
public(anywhere),protected(self and subclasses),private(self only). __construct()- constructor (two underscores).__destruct()- destructor, called when object is destroyed.staticproperties/methods: can be accessed without instantiation viaself::orClassName::. Static varibale changes affect all instances.- Class constants: declared with
const, immutable, accessed similarly. finalkeyword: on class prevents inheritance, on method prevents overriding (not applicable to properties).
class Animal{
public $name;
public $age;
public static $color;
const AREA = "china";
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
Animal::$color = "white";
echo "Constructor executed" . PHP_EOL;
}
public function eat(){
echo self::AREA . "'s " . self::$color . " " . $this->name . " is eating" . PHP_EOL;
}
public function __destruct(){
}
}
$cat = new Animal("tom","5");
echo $cat->name . PHP_EOL;
echo Animal::$color . PHP_EOL;
$cat->eat();
Animal::$color = "black";
$cat->eat();
/* Output:
Constructor executed
tom
white
china's white tom is eating
china's black tom is eating
*/
extendsfor inheritance.- Call parent constructor via
parent::__construct().