PHP Summary

Basics

  1. Code is written inside <?php ?> tags.
  2. echo outputs one or more strings separated by commas, concatenated with dots.
  3. PHP_EOL is the newline constant.
  4. print outputs only one string and always returns 1.
  5. Ternary operator ?: e.g., 1+2==3 ? 4 : 5 returns 4 if true, else 5.
  6. Null coalescing operator ??: $a ?? "b" returns $a if defined and not null, otherwise "b".
  7. 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.
  8. isset($a) returns true if variable is declared and not null.
  9. is_null($a) returns true if value is null; throws notice if undefined.
  10. empty($a) returns true for 0, false, null, empty array, empty string, and undefined (though not recommended for checking undefined variables).

Loops

  1. switch loops require break to 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!";
}
  1. continue skips the rest of the current loop iteration and proceeds to the next one. It does not exit the loop.
  2. break exits 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

  1. Addition (+): Merges two arrays. For duplicate keys, the element from the left array is kept; unique keys are appended.
  2. array_merge($a, $b): Similar to addition but for duplicate keys, the right array's value overrides the left's.
  3. 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

  1. strlen() - string length (1 for English char, 3 for Chinese char usually)
  2. strpos($str, "xxx") - find first occurrence position, returns false if not found
  3. stripos() - case-insensitive version
  4. strrpos() - find last occurrence position
  5. strripos() - case-insensitive last occurrence
  6. explode(",", $str) - split string into array by delimiter
  7. implode(",", $str) - join array elements into string with delimiter
  8. strtoupper() - convert to uppercase
  9. strtolower() - convert to lowercase
  10. str_replace($search, $replace, $str) - replace occurrences
  11. trim() - strip whitespace from both ends
  12. substr() - extract substring
  13. 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

  1. date('Y-m-d h-m-s') - date/time formatting (Y=year with century, y=two-digit year)
  2. 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

  1. Constants are named without $, case-sensitive (convention uppercase), global by default.
  2. Once defined, cannot be changed or undefined.
  3. const cannot 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.
  4. get_defined_constants() retrieves all constants.
define("NAME", "This is a constant");
const NAME2 = "Another constant";

File Inclusion

  1. require
  2. include - syntax: include "./xx.php";

Classes

  1. Access members and methods with ->.
  2. Access control: public (anywhere), protected (self and subclasses), private (self only).
  3. __construct() - constructor (two underscores).
  4. __destruct() - destructor, called when object is destroyed.
  5. static properties/methods: can be accessed without instantiation via self:: or ClassName::. Static varibale changes affect all instances.
  6. Class constants: declared with const, immutable, accessed similarly.
  7. final keyword: 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
*/
  1. extends for inheritance.
  2. Call parent constructor via parent::__construct().

Tags: PHP programming Syntax

Posted on Tue, 02 Jun 2026 17:51:52 +0000 by dfowler