logo
💻 编程语言

PHP

PHP Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 编程语言🧭 Markdown 速查🏷️ 2 个标签
#php#web
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

hello.php
PHP
滚动查看更多
<?php // begin with a PHP open tag.

echo "Hello World\n";
print("Hello cheatsheets.zip");

?>

PHP run command

SHELL
滚动查看更多
$ php hello.php
Variables
PHP
滚动查看更多
$boolean1 = true;
$boolean2 = True;

$int = 12;
$float = 3.1415926;
unset($float);  // Delete variable

$str1 = "How are you?";
$str2 = 'Fine, thanks';

See: Types

Strings
PHP
滚动查看更多
$url = "cheatsheets.zip";
echo "I'm learning PHP at $url";

// Concatenate strings
echo "I'm learning PHP at " . $url;

$hello = "Hello, ";
$hello .= "World!";
echo $hello;   # => Hello, World!

See: Strings

Arrays
PHP
滚动查看更多
$num = [1, 3, 5, 7, 9];
$num[5] = 11;
unset($num[2]);    // Delete variable
print_r($num);     # => 1 3 7 9 11
echo count($num);  # => 5

See: Arrays

Operators
PHP
滚动查看更多
$x = 1;
$y = 2;

$sum = $x + $y;
echo $sum;   # => 3

See: Operators

Include

vars.php

PHP
滚动查看更多
<?php // begin with a PHP open tag.
$fruit = 'apple';
echo "I was imported";
return 'Anything you like.';
?>

test.php

PHP
滚动查看更多
<?php
include 'vars.php';
echo $fruit . "\n";   # => apple

/* Same as include,
cause an error if cannot be included*/
require 'vars.php';

// Also works
include('vars.php');
require('vars.php');

// Include through HTTP
include 'http://x.com/file.php';

// Include and the return statement
$result = include 'vars.php';
echo $result;  # => Anything you like.
?>
Functions
PHP
滚动查看更多
function add($num1, $num2 = 1) {
    return $num1 + $num2;
}
echo add(10);    # => 11
echo add(10, 5); # => 15

See: Functions

Comments
PHP
滚动查看更多
# This is a one line shell-style comment

// This is a one line c++ style comment

/* This is a multi line comment
   yet another line of comment */
Constants
PHP
滚动查看更多
const MY_CONST = "hello";

echo MY_CONST;   # => hello

# => MY_CONST is: hello
echo 'MY_CONST is: ' . MY_CONST;
Classes
PHP
滚动查看更多
class Student {
    public function __construct($name) {
        $this->name = $name;
    }
}
$alex = new Student("Alex");

See: Classes

PHP Types

Boolean
PHP
滚动查看更多
$boolean1 = true;
$boolean2 = TRUE;
$boolean3 = false;
$boolean4 = FALSE;

$boolean5 = (boolean) 1;   # => true
$boolean6 = (boolean) 0;   # => false

Boolean are case-insensitive

Integer
PHP
滚动查看更多
$int1 = 28;    # => 28
$int2 = -32;   # => -32
$int3 = 012;   # => 10 (octal)
$int4 = 0x0F;  # => 15 (hex)
$int5 = 0b101; # => 5  (binary)

# => 2000100000 (decimal, PHP 7.4.0)
$int6 = 2_000_100_000;

See also: Integers

Strings
PHP
滚动查看更多
echo 'this is a simple string';

See: Strings

Arrays
PHP
滚动查看更多
$arr = array("hello", "world", "!");

See: Arrays

Float (Double)
PHP
滚动查看更多
$float1 = 1.234;
$float2 = 1.2e7;
$float3 = 7E-10;

$float4 = 1_234.567;  // as of PHP 7.4.0
var_dump($float4);    // float(1234.567)

$float5 = 1 + "10.5";   # => 11.5
$float6 = 1 + "-1.3e3"; # => -1299
Null
PHP
滚动查看更多
$a = null;
$b = 'Hello php!';
echo $a ?? 'a is unset'; # => a is unset
echo $b ?? 'b is unset'; # => Hello php

$a = array();
$a == null    # => true
$a === null   # => false
is_null($a)   # => false
Iterables
PHP
滚动查看更多
function bar(): iterable {
    return [1, 2, 3];
}
function gen(): iterable {
    yield 1;
    yield 2;
    yield 3;
}
foreach (bar() as $value) {
    echo $value;   # => 123
}

PHP Strings

String
PHP
滚动查看更多
# => '$String'
$sgl_quotes = '$String';

# => 'This is a $String.'
$dbl_quotes = "This is a $sgl_quotes.";

# => a 	 tab character.
$escaped   = "a \t tab character.";

# => a slash and a t: \t
$unescaped = 'a slash and a t: \t';
Multi-line
PHP
滚动查看更多
$str = "foo";

// Uninterpolated multi-liners
$nowdoc = <<<'END'
Multi line string
$str
END;

// Will do string interpolation
$heredoc = <<<END
Multi line
$str
END;
Manipulation
PHP
滚动查看更多
$s = "Hello Phper";
echo strlen($s);       # => 11

echo substr($s, 0, 3); # => Hel
echo substr($s, 1);    # => ello Phper
echo substr($s, -4, 3);# => hpe

echo strtoupper($s);   # => HELLO PHPER
echo strtolower($s);   # => hello phper

echo strpos($s, "l");      # => 2
var_dump(strpos($s, "L")); # => false

See: String Functions

PHP Arrays

Defining
PHP
滚动查看更多
$a1 = ["hello", "world", "!"]
$a2 = array("hello", "world", "!");
$a3 = explode(",", "apple,pear,peach");

Mixed int and string keys

PHP
滚动查看更多
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array);

Short array syntax

PHP
滚动查看更多
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
Multi array
PHP
滚动查看更多
$multiArray = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

print_r($multiArray[0][0]) # => 1
print_r($multiArray[0][1]) # => 2
print_r($multiArray[0][2]) # => 3
Multi type
PHP
滚动查看更多
$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dim" => array(
             "a" => "foo"
         )
    )
);

# => string(3) "bar"
var_dump($array["foo"]);

# => int(24)
var_dump($array[42]);

# =>  string(3) "foo"
var_dump($array["multi"]["dim"]["a"]);
manipulation
PHP
滚动查看更多
$arr = array(5 => 1, 12 => 2);
$arr[] = 56;      // Append
$arr["x"] = 42;   // Add with key
sort($arr);       // Sort
unset($arr[5]);   // Remove
unset($arr);      // Remove all

See: Array Functions

Indexing iteration
PHP
滚动查看更多
$array = array('a', 'b', 'c');
$count = count($array);

for ($i = 0; $i < $count; $i++) {
    echo "i:{$i}, v:{$array[$i]}\n";
}
Value iteration
PHP
滚动查看更多
$colors = array('red', 'blue', 'green');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}
Key iteration
PHP
滚动查看更多
$arr = ["foo" => "bar", "bar" => "foo"];

foreach ( $arr as $key => $value )
{
  	echo "key: " . $key . "\n";
    echo "val: {$arr[$key]}\n";
}
Concatenate arrays
PHP
滚动查看更多
$a = [1, 2];
$b = [3, 4];

// PHP 7.4 later
# => [1, 2, 3, 4]
$result = [...$a, ...$b];
Into functions
PHP
滚动查看更多
$array = [1, 2];

function foo(int $a, int $b) {
	echo $a; # => 1
  	echo $b; # => 2
}
foo(...$array);
Splat Operator
PHP
滚动查看更多
function foo($first, ...$other) {
	var_dump($first); # => a
  	var_dump($other); # => ['b', 'c']
}
foo('a', 'b', 'c' /*, ...*/ );
// or
function foo($first, string ...$other){}

PHP Operators

Arithmetic
--
+Addition
-Subtraction
*Multiplication
/Division
%Modulo
**Exponentiation
Assignment
--
a += bSame as a = a + b
a -= bSame as a = a – b
a *= bSame as a = a * b
a /= bSame as a = a / b
a %= bSame as a = a % b
Comparison
--
==Equal
===Identical
!=Not equal
<>Not equal
!==Not identical
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal
<=>Less than/equal/greater than
Logical

| - | - | | ----- | ------------ | --- | --- | | and | And | | or | Or | | xor | Exclusive or | | ! | Not | | && | And | | | | | Or |

Arithmetic
PHP
滚动查看更多
// Arithmetic
$sum        = 1 + 1; // 2
$difference = 2 - 1; // 1
$product    = 2 * 2; // 4
$quotient   = 2 / 1; // 2

// Shorthand arithmetic
$num = 0;
$num += 1;       // Increment $num by 1
echo $num++;     // Prints 1 (increments after evaluation)
echo ++$num;     // Prints 3 (increments before evaluation)
$num /= $float;  // Divide and assign the quotient to $num
Bitwise

| - | - | | ---- | ------------------ | ----------------- | | & | And | | | | Or (inclusive or) | | ^ | Xor (exclusive or) | | ~ | Not | | << | Shift left | | >> | Shift right |

PHP Conditionals

If elseif else
PHP
滚动查看更多
$a = 10;
$b = 20;

if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
Switch
PHP
滚动查看更多
$x = 0;
switch ($x) {
    case '0':
        print "it's zero";
        break;
    case 'two':
    case 'three':
        // do something
        break;
    default:
        // do something
}
Ternary operator
PHP
滚动查看更多
# => Does
print (false ? 'Not' : 'Does');

$x = false;
# => Does
print($x ?: 'Does');

$a = null;
$b = 'Does print';
# => a is unset
echo $a ?? 'a is unset';
# => print
echo $b ?? 'b is unset';
Match
PHP
滚动查看更多
$statusCode = 500;
$message = match($statusCode) {
  200, 300 => null,
  400 => 'not found',
  500 => 'server error',
  default => 'known status code',
};
echo $message; # => server error

See: Match

Match expressions
PHP
滚动查看更多
$age = 23;

$result = match (true) {
    $age >= 65 => 'senior',
    $age >= 25 => 'adult',
    $age >= 18 => 'young adult',
    default => 'kid',
};

echo $result; # => young adult

PHP Loops

while
PHP
滚动查看更多
$i = 1;
# => 12345
while ($i <= 5) {
    echo $i++;
}
do while
PHP
滚动查看更多
$i = 1;
# => 12345
do {
    echo $i++;
} while ($i <= 5);
for i
PHP
滚动查看更多
# => 12345
for ($i = 1; $i <= 5; $i++) {
    echo $i;
}
break
PHP
滚动查看更多
# => 123
for ($i = 1; $i <= 5; $i++) {
    if ($i === 4) {
        break;
    }
    echo $i;
}
continue
PHP
滚动查看更多
# => 1235
for ($i = 1; $i <= 5; $i++) {
    if ($i === 4) {
        continue;
    }
    echo $i;
}
foreach
PHP
滚动查看更多
$a = ['foo' => 1, 'bar' => 2];
# => 12
foreach ($a as $k) {
    echo $k;
}

See: Array iteration

PHP Functions

Returning values
PHP
滚动查看更多
function square($x)
{
    return $x * $x;
}

echo square(4);  # => 16
Return types
PHP
滚动查看更多
// Basic return type declaration
function sum($a, $b): float {/*...*/}
function get_item(): string {/*...*/}

class C {}
// Returning an object
function getC(): C { return new C; }
Nullable return types
PHP
滚动查看更多
// Available in PHP 7.1
function nullOrString(int $v) : ?string
{
    return $v % 2 ? "odd" : null;
}
echo nullOrString(3);       # => odd
var_dump(nullOrString(4));  # => NULL

See: Nullable types

Void functions
PHP
滚动查看更多
// Available in PHP 7.1
function voidFunction(): void
{
	echo 'Hello';
	return;
}

voidFunction();  # => Hello
Variable functions
PHP
滚动查看更多
function bar($arg = '')
{
    echo "In bar(); arg: '$arg'.\n";
}

$func = 'bar';
$func('test'); # => In bar(); arg: test
Anonymous functions
PHP
滚动查看更多
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World'); # => Hello World
$greet('PHP');   # => Hello PHP
Recursive functions
PHP
滚动查看更多
function recursion($x)
{
    if ($x < 5) {
        echo "$x";
        recursion($x + 1);
    }
}
recursion(1);  # => 1234
Default parameters
PHP
滚动查看更多
function coffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
# => Making a cup of cappuccino.
echo coffee();
# => Making a cup of .
echo coffee(null);
# => Making a cup of espresso.
echo coffee("espresso");
Arrow Functions
PHP
滚动查看更多
$y = 1;

$fn1 = fn($x) => $x + $y;

// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
    return $x + $y;
};
echo $fn1(5);   # => 6
echo $fn2(5);   # => 6

PHP Classes

Constructor
PHP
滚动查看更多
class Student {
    public function __construct($name) {
        $this->name = $name;
    }
  	public function print() {
        echo "Name: " . $this->name;
    }
}
$alex = new Student("Alex");
$alex->print();    # => Name: Alex
Inheritance
PHP
滚动查看更多
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
Classes variables
PHP
滚动查看更多
class MyClass
{
    const MY_CONST       = 'value';
    static $staticVar    = 'static';

    // Visibility
    public static $var1  = 'pubs';

    // Class only
    private static $var2 = 'pris';

    // The class and subclasses
    protected static $var3 = 'pros';

    // The class and subclasses
    protected $var6      = 'pro';

    // The class only
    private $var7        = 'pri';
}

Access statically

PHP
滚动查看更多
echo MyClass::MY_CONST;   # => value
echo MyClass::$staticVar; # => static
Magic Methods
PHP
滚动查看更多
class MyClass
{
    // Object is treated as a String
    public function __toString()
    {
        return $property;
    }
    // opposite to __construct()
    public function __destruct()
    {
        print "Destroying";
    }
}
Interface
PHP
滚动查看更多
interface Foo
{
    public function doSomething();
}
interface Bar
{
    public function doSomethingElse();
}
class Cls implements Foo, Bar
{
    public function doSomething() {}
    public function doSomethingElse() {}
}

PHP Trait

Trait declaration & Use case
PHP
滚动查看更多
// Declare Trait allows reuse of code
// across multiple classes for common characteristics or use cases

<?php
trait Logger {
    public function log($message) {
    	$date = new DateTime();
        echo "| ".  $date->format('Y-m-d H:i:s') . " | " . $message;
    }
}

// Use case :
// Call trait with "use <trait name> in Class"

class User {
    use Logger;

    public function createUser() {
        // User creation logic
        $this->log("User created.");
    }
}

class Product {
    use Logger;

    public function createProduct() {
        // Product creation logic
        $this->log("Product created.");
    }
}

$user = new User();
$user->createUser(); // Output ex: | 2025-06-18 14:06:09 | User created.

$product = new Product();
$product->createProduct(); // Output ex: | 2025-06-18 14:06:09 | Product created.

PHP Enums (PHP 8.1)

Enum Declaration & Use case
PHP
滚动查看更多
<?php
// enum is a data type that allows you to define a set of named constants,
// representing a fixed group of related values

enum Status {
    case Pending;
    case Approved;
    case Rejected;
}

// Use case

function getStatusMessage(Status $status): string {
    return match($status) {
        Status::Pending => "Waiting for approval.",
        Status::Approved => "Your request has been approved.",
        Status::Rejected => "Your request has been rejected.",
    };
}

$currentStatus = Status::Approved;
echo getStatusMessage($currentStatus); // Output : Your request has been approved.

PHP Date & Time Handling

Current date and time
PHP
滚动查看更多
// DateTime in PHP handles both date and time

<?php
$now = new DateTime();
echo $now->format('Y-m-d H:i:s.u');

// Output ex: 2024-04-27 14:35:22.123456
Creating specific date/time objects
PHP
滚动查看更多
<?php
// Create a date object
$d = new DateTime('2024-04-27');
echo $d->format('Y-m-d');

// Output : 2024-04-27

// Create a time object
$t = new DateTime('15:30:45');
echo $t->format('H:i:s');

// Output : 15:30:45

// Create a datetime object
$dt = new DateTime('2024-04-27 15:30:45');
echo $dt->format('Y-m-d H:i:s');

// Output :  2024-04-27 15:30:45
Converting between date formats
PHP
滚动查看更多
<?php
// Convert a string to a DateTime object
$date_str = "2024-04-27 14:00";
$dt_obj = new DateTime($date_str);
echo $dt_obj->format('Y-m-d H:i:s');

// Output : 2024-04-27 14:00:0027

// Convert a DateTime object to a string
$formatted_str = $dt_obj->format('d/m/Y H:i');
echo $formatted_str;

// Output :  27/04/2024 14:00
Timestamps and Unix time
PHP
滚动查看更多
<?php
// Get current timestamp
$timestamp = time();
echo $timestamp;

// Output ex:  1750253583

// Convert timestamp back to DateTime
$dt_from_timestamp = (new DateTime())->setTimestamp($timestamp);
echo $dt_from_timestamp->format('Y-m-d H:i:s');

// Output ex : 2025-06-18 13:33:03
Date difference and timedelta
PHP
滚动查看更多
<?php
$date1 = new DateTime('2024-04-27');
$date2 = new DateTime('2024-05-01');

$interval = $date1->diff($date2);
echo $interval->days;

// Output : 4

// Using DateInterval for date arithmetic
$new_date = clone $date1;
$new_date->add(new DateInterval('P10D'));
echo $new_date->format('Y-m-d');

// Output : 2024-05-07

Miscellaneous

Basic error handling
PHP
滚动查看更多
try {
    // Do something
} catch (Exception $e) {
    // Handle exception
} finally {
    echo "Always print!";
}
Exception in PHP 8.0
PHP
滚动查看更多
$nullableValue = null;

try {
	$value = $nullableValue ?? throw new InvalidArgumentException();
} catch (InvalidArgumentException) { // Variable is optional
    // Handle my exception
    echo "print me!";
}
Custom exception
PHP
滚动查看更多
class MyException extends Exception {
    // do something
}

Usage

PHP
滚动查看更多
try {
    $condition = true;
    if ($condition) {
        throw new MyException('bala');
    }
} catch (MyException $e) {
    // Handle my exception
}
Nullsafe Operator
PHP
滚动查看更多
// As of PHP 8.0.0, this line:
$result = $repo?->getUser(5)?->name;

// Equivalent to the following code:
if (is_null($repo)) {
    $result = null;
} else {
    $user = $repository->getUser(5);
    if (is_null($user)) {
        $result = null;
    } else {
        $result = $user->name;
    }
}

See also: Nullsafe Operator

Regular expressions
PHP
滚动查看更多
$str = "Visit cheatsheets.zip";
echo preg_match("/ch/i", $str); # => 1

See: Regex in PHP

fopen() mode
--
rRead
r+Read and write, prepend
wWrite, truncate
w+Read and write, truncate
aWrite, append
a+Read and write, append
Super Global Variables
VariableDescription
$_SERVERHolds information about headers, paths, and script locations
$_GETContains data sent via URL parameters (query string)
$_POSTContains data sent via HTTP POST method
$_FILESContains information about uploaded files
$_COOKIEContains cookie data
$_SESSIONStores session variables
$_REQUESTContains data from $_GET, $_POST, and $_COOKIE
$_ENVContains environment variables
$GLOBALSReferences all global variables available in the script

{.left-text}

Super Global Variables are built-in variables always available in all scopes.

Runtime defined Constants
PHP
滚动查看更多
define("CURRENT_DATE", date('Y-m-d'));

// One possible representation
echo CURRENT_DATE;   # => 2021-01-05

# => CURRENT_DATE is: 2021-01-05
echo 'CURRENT_DATE is: ' . CURRENT_DATE;

Also see

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572