PHP CheatSheet

PHP developers, are you tired of wasting precious time searching for code snippets, functions, and syntax online? Look no further than the PHP Cheat Sheet – the ultimate resource for all your PHP development needs.

This sleek and sophisticated reference tool is designed to provide you with quick and easy access to everything you need to build powerful web applications. From basic language constructs to advanced object-oriented programming techniques, the PHP Cheat Sheet has it all.

With its intuitive layout and visually appealing design, this cheat sheet makes it simple to find the information you need at a glance. No more scouring through documentation or endless Google searches, save yourself time and effort by having all the essential PHP knowledge at your fingertips.

And with regular updates to keep pace with changes in the PHP language, the PHP Cheat Sheet is always up-to-date and relevant. So whether you're an experienced PHP developer or just starting out, this comprehensive guide will help you streamline your workflow and take your coding skills to the next level.

In short, the PHP Cheat Sheet is the must-have resource that every serious PHP developer needs in their toolkit. So why wait? Download your copy today and experience the power of efficient, effective PHP development!


Table of Content




# Getting started in PHP


What is PHP?

1. PHP is an acronym for "PHP: Hypertext Preprocessor"

2. PHP is a widely-used, open source scripting language

3. PHP scripts are executed on the server

4. PHP is free to download and use


PHP is an amazing and popular language!

1. It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!

2. It is deep enough to run the largest social network (Facebook)!

3. It is also easy enough to be a beginner's first server side language!

helloworld.php

<?php 
    // begin with a PHP open tag.
    echo "Hello World\n";
    print("Hello Google.com");
?>

PHP run command

$ php helloworld.php

Variables

$boolean1 = true;
$boolean2 = True;

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

$str1 = "What is your name?";
$str2 = 'I am Jack';

Strings

$url = "Google.com";
echo "I'm learning PHP at $url";
// Outputs: I'm learning PHP at Google.com

// Concatenate strings
echo "I'm learning PHP at " . $url;
// Outputs: I'm learning PHP at Google.com

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

Arrays

$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

Operators

$x = 1;
$y = 2;

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

Include

vars.php


<?php 
    // begin with a PHP open tag.
    $fruit = 'banana';
    echo "I was imported";
    return 'Anything you like.';
?>

test.php

    
<?php 
    include 'vars.php';
    echo $fruit . "\n";   
    // Outputs: banana

    /* 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;  
    // Outputs: Anything you like.
?>
    

Functions

function add($num1, $num2 = 1) {
    return $num1 + $num2;
}

echo add(10);    
// Outputs: 11

echo add(10, 5);
// Outputs: 15

Comments

# This is a one line comment

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

/* This is a multi line comment */

Constants

const MY_CONST = "Hello World";

echo MY_CONST;
// Outputs: Hello World

echo 'MY_CONST is: ' . MY_CONST; 
// Outputs: MY_CONST is: Hello World

Classes

class Student {
    public function __construct($name) {
        $this->name = $name;
    }
}
$alex = new Student("Jack");

# Types in PHP


Boolean

$boolean1 = true;
$boolean2 = TRUE;
$boolean3 = false;
$boolean4 = FALSE;

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

Integer

$int1 = 28;    // Outputs: 28
$int2 = -32;   // Outputs: -32
$int3 = 012;   // Outputs: 10 (octal)
$int4 = 0x0F;  // Outputs: 15 (hex)
$int5 = 0b101; // Outputs: 5  (binary)

// Outputs: 2000100000 (decimal, PHP 7.4.0)
$int6 = 2_000_100_000;

Strings

echo 'Hello World';

Arrays

$arr = array("hello", "world", "!");

Float (Double)

$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";   
// Outputs: 11.5
$float6 = 1 + "-1.3e3"; 
// Outputs: -1299

Null

$a = null;
$b = 'Hello php!';
echo $a ?? 'a is unset'; // Outputs: a is unset
echo $b ?? 'b is unset'; // Outputs: Hello php

$a = array();
$a == null    // Outputs: true
$a === null   // Outputs: false
is_null($a)   // Outputs: false

Iterables

function bar(): iterable {
    return [1, 2, 3];
}


function gen(): iterable {
    yield 1;
    yield 2;
    yield 3;
}


foreach (bar() as $value) {
    echo $value;  
     // Outputs: 123
} 

# Strings in PHP


String

$sgl_quotes = '$Hello';
// Outputs: '$Hello'

$dbl_quotes = "This is a $sgl_quotes.";
// Outputs: 'This is a $Hello.'

$escaped   = "a \t tab character.";
// Outputs: a 	 tab character.

$unescaped = 'a slash and a t: \t';
// Outputs: a slash and a t: \t

Multi-line

$str = "foo";

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

// Will do string interpolation
$heredoc = <<<END
Multi line
$str
END;

Manipulation

$s = "Hello Phper";
echo strlen($s);       
// Outputs: 11

echo substr($s, 0, 3); 
// Outputs: Hel

echo substr($s, 1);    
// Outputs: ello Phper

echo substr($s, -4, 3);
// Outputs: hpe

echo strtoupper($s);   
// Outputs: HELLO PHPER

echo strtolower($s);   
// Outputs: hello phper

echo strpos($s, "l");      
// Outputs: 2

var_dump(strpos($s, "L")); 
// Outputs: false

# Arrays in PHP


Defining

$a1 = ["hello", "world", "everyone!"]

$a2 = array("hello", "world", "everyone!");

$a3 = explode(",", "apple, pear, peach, banana");

Multi array

$multiArray = [ 
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

print_r($multiArray[0][0]) 
// Outputs: 1

print_r($multiArray[0][1]) 
// Outputs: 2

print_r($multiArray[0][2]) 
// Outputs: 3

Multi type

$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dim" => array(
             "a" => "foo"
         )
    )
);

var_dump($array["foo"]);
// Outputs: string(3) "bar"

var_dump($array[42]); 
// Outputs: int(24)   

var_dump($array["multi"]["dim"]["a"]);
// Outputs:  string(3) "foo"

manipulation

$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

Indexing iteration

$array = array('a', 'b', 'c');
$count = count($array);

for ($i = 0; $i < $count; $i++) {
    echo "i:{$i}, v:{$array[$i]}\n";
}

Value iteration

$colors = array('yellow', 'gray', 'green');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

Key iteration

$arr = ["foo" => "bar", "bar" => "foo"];

foreach ( $arr as $key => $value )
{
    echo "key: " . $key . "\n";
    echo "val: {$arr[$key]}\n";
}

Concatenate arrays

$a = [1, 2];
$b = [3, 4];

// PHP 7.4 later
$result = [...$a, ...$b];
// Outputs: [1, 2, 3, 4]

Into functions

$array = [1, 2];

function foo(int $a, int $b) {
	echo $a; 
    // Outputs: 1

  	echo $b; 
    // Outputs: 2
}

foo(...$array);

Splat Operator

function foo($first, ...$other) {
	var_dump($first); 
    // Outputs: a

  	var_dump($other); 
    // Outputs: ['b', 'c']
}

foo('a', 'b', 'c' /*, ...*/ );
// or
function foo($first, string ...$other){}

# Operators in PHP


Arithmetic

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
** Exponentiation

Assignment

a += b Same as a = a + b
a -= b Same as a = a b
a *= b Same as a = a * b
a /= b Same as a = a / b
a %= b Same 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

// 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

# Conditionals in PHP


If elseif else

$a = 12;
$b = 22;

if ($a > $b) {
    echo "a is greater than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is less than b";
}

// Outputs: a is less than b

Switch

$x = 0;
switch ($x) {
    case '0':
        print "zero";
        break; 
    case 'two':
    case 'three':
        // do something
        break;
    default:
        // do something
        break;
}

// Outputs: zero

Ternary operator

print (false ? 'Not' : 'Does');
// Outputs: Does

$x = false;
print($x ?: 'Does');
// Outputs: Does

$a = null;
$b = 'Does print';
echo $a ?? 'a is unset';
// Outputs: a is unsert

echo $b ?? 'b is unset';
// Outputs: print

Match

$statusCode = 500;

$message = match($statusCode) {
  200, 300 => null,
  400 => 'HTTP Status Not Found',
  500 => 'HTTP Status Internal Error Server',
  default => 'UnKnown HTTP Status Not Found',
};

echo $message; 
// Outputs: HTTP Status Internal Error Server

Match expressions

$age = 24;

$result = match (true) {
    $age >= 65 => 'You are Senior',
    $age >= 25 => 'You are Adult',
    $age >= 18 => 'Your are Young adult',
    default => 'You are Kid',
};

echo $result; 
// Outputs: Your are Young adult

# Loops in PHP


while

$i = 1;
while ($i <= 7) {
    echo $i++;
}

// Outputs: 1234567

do while

$i = 1;

do {
    echo $i++;
} while ($i <= 7);

// Outputs: 1234567

for

for ($i = 1; $i <= 7; $i++) {
    echo $i;
}

// Outputs: 1234567

break

for ($i = 0; $i <= 5; $i++) {
    if ($i === 4) {
        break;
    }
    echo $i;
}

// Outputs: 0123

continue

for ($i = 0; $i <= 5; $i++) {
    if ($i === 4) {
        continue;
    }
    echo $i;
}

// Outputs: 01235

foreach

$a = ['foo' => 1, 'bar' => 2];

foreach ($a as $k) {
    echo $k;
}

// Outputs: 12

# Functions in PHP


Returning values

function add($x)
{
    return $x + $x;
}

echo add(4);  
// Outputs: 8

Return types

// 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

// Available in PHP 7.1
function nullOrString(int $v) : ?string
{
    return $v % 2 ? "odd" : null;
}

echo nullOrString(3);       
// Outputs: odd

var_dump(nullOrString(4));  
// Outputs: NULL

Void functions

// Available in PHP 7.1
function voidFunction(): void
{
	echo 'Hello World';
	return;
}

voidFunction();  
// Outputs: Hello World

Variable functions

function bar($arg = '')
{
    echo "In bar(); arg: '$arg'.\n";
}

$func = 'bar';
$func('Hello World'); 

// Outputs: In bar(); arg: Hello World

Anonymous functions

$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World'); 
// Outputs: Hello World

$greet('PHP');   
// Outputs: Hello PHP

Recursive functions

function recursion($x)
{
    if ($x < 7) {
        echo "$x";
        recursion($x + 1);
    }
}

recursion(1);  
// Outputs: 123456

Default parameters

function coffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}

echo coffee();
// Outputs: Making a cup of cappuccino.

echo coffee(null);
// Outputs: Making a cup of.

echo coffee("espresso");
// Outputs: Making a cup of espresso.

Arrow Functions

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

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

echo $fn2(5);   
// Outputs: 6

# Classes in PHP


Constructor

class Student {
    public function __construct($name) {
        $this -> name = $name;
    }

  	public function print() {
        echo "Student Name: " . $this -> name;
    }
}

$alex = new Student("Alex");
$alex -> print();    

// Outputs: Student Name: Alex

Inheritance

class ExtendClass extends SupperClass
{
    // Override the function method of parent class
    function displayVar()
    {
        echo "This is Extend class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();

// Outputs: This is Extend class

Classes variables

class MyClass
{
    const MY_CONST       = 'myConst';
    static $staticVar    = 'staticValue';

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

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

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

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

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


echo MyClass::MY_CONST;   
// Outputs: myConst

echo MyClass::$staticVar; 
// Outputs: staticValue

Magic Methods

class MyClass
{
    // Object is treated as a String
    public function __toString()
    {
        return $property;
    }

    // opposite to __construct()
    public function __destruct()
    {
        print "Destroying !!!!!";
    }
}

Interface

interface Foo 
{
    public function doSomething();
}


interface Bar
{
    public function doSomethingElse();
}


class Cls implements Foo, Bar 
{
    public function doSomething() {}
    public function doSomethingElse() {}
}

# Miscellaneous in PHP


Try Catch Exception

try {
    // Write your logic code here
    // ....

} catch (Exception $ex) {
    // Handle your exception at here

} finally {
    echo "Always print!";
}

PHP 8.0 Exception handler

$nullableValue = null;

try {
	$value = $nullableValue ?? throw new InvalidArgumentException();
} catch (InvalidArgumentException) { // Variable is optional
    // Handle my exception
    echo "Message Exception throw here !!!";
}

// Outputs: Message Exception throw here !!!

Custom exception


class MyException extends Exception {
    // Do your logic here...
}


try {
    $condition = true;
    if ($condition) {
        throw new MyException('MyException occur !!!');
    }
} catch (MyException $e) {
    // Handle my exception
}

Nullsafe Operator

// 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;
    }
}

Regular expressions

$str = "Visit Google";
echo preg_match("/Googl/i", $str); 
// Outputs: 1


$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "Google", $str); 
// Outputs "Visit Google!"

fopen() mode

r Read
r+ Read and write, prepend
w Write, truncate
w+ Read and write, truncate
a Write, append
a+ Read and write, append

Runtime defined Constants

define("CURRENT_DATE", date('Y-m-d'));

// One possible representation
echo CURRENT_DATE;   
// Outputs: 2021-10-04

echo 'Today is: ' . CURRENT_DATE; 
// Outputs: Today is: 2021-10-04


Best Suggest