SlamariSlamariSlamari
  • Web Technologies
  • Web3 & Blockchain
  • Software
  • Scholarships
  • Remote Tech Jobs
  • Phones Review
  • AI & Emerging Tech
Search
© 2026 Slamari Global Tech. All Rights Reserved.
Font ResizerAa
Font ResizerAa
SlamariSlamari
  • Web Technologies
  • Web3 & Blockchain
  • Software
  • Scholarships
  • Remote Tech Jobs
  • Phones Review
  • AI & Emerging Tech
  • Web Technologies
  • Web3 & Blockchain
  • Software
  • Scholarships
  • Remote Tech Jobs
  • Phones Review
  • AI & Emerging Tech
© 2026 Slamari Global Tech. All Rights Reserved.

Home - general post - PHP Cheatsheet: Quick Reference Guide for Developers

general post

PHP Cheatsheet: Quick Reference Guide for Developers

Faisal Salisu
Last updated: March 21, 2026 5:25 pm
Faisal Salisu
Share
PHP cheatsheet

PHP Cheatsheet: Your Essential Guide to Modern PHP Development

PHP, a widely-used open-source scripting language, has been the backbone of countless websites and web applications for decades. From simple personal blogs to complex enterprise systems, PHP’s versatility and robust ecosystem make it a go-to choice for web developers worldwide. This cheatsheet is designed to be your quick reference guide, covering essential syntax, core concepts, and common functions in modern PHP development.

Contents
PHP Cheatsheet: Your Essential Guide to Modern PHP Development1. Fundamentals: Syntax and Basic ConstructsPHP Tags and CommentsStatements and SemicolonsVariables and ConstantsVariablesConstantsData TypesScalar TypesCompound TypesSpecial Types2. OperatorsArithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsIncrement/Decrement OperatorsString OperatorTernary OperatorNull Coalescing Operator (??, PHP 7+)3. Control FlowConditional Statementsif, else if, elseswitchLoopsfor Loopforeach Loopwhile Loopdo-while Loopbreak and continue4. FunctionsDefining and Calling FunctionsParameters and Return TypesAnonymous Functions (Closures)Arrow Functions (fn, PHP 7.4+)5. ArraysIndexed ArraysAssociative ArraysMultidimensional ArraysCommon Array Functions

Whether you’re a seasoned developer needing a quick reminder or a newcomer looking for a structured overview, this guide will help you navigate the fundamentals and advanced features of PHP efficiently.

1. Fundamentals: Syntax and Basic Constructs

PHP code is typically embedded within HTML. The server processes the PHP code and sends the resulting HTML to the client’s browser.

PHP Tags and Comments

PHP code blocks are enclosed within special tags.

- Advertisement -
- Advertisement -
  • Standard Tags: <?php ... ?> (Recommended)
  • Short Echo Tag: <?= ... ?> (Shorthand for <?php echo ... ?>, useful for displaying variables quickly)
<?php
// This is a single-line comment

/
  This is a multi-line comment block.
  It can span multiple lines.
 /

echo "Hello, World!"; // This is also a single-line comment
?>

<p>The current year is: <?= date('Y'); ?></p>

Statements and Semicolons

Every statement in PHP must end with a semicolon (;), except for the closing tag of a PHP block.

<?php
$name = "Alice";
echo "My name is " . $name; // Semicolon required
?>

Variables and Constants

Variables

  • Variables start with a dollar sign ($).
  • They are case-sensitive ($name is different from $Name).
  • No explicit type declaration is needed; PHP is dynamically typed.
<?php
$age = 30;         // Integer
$name = "Bob";     // String
$is_active = true; // Boolean

echo $name . " is " . $age . " years old.";
?>

Constants

  • Defined using define() function or the const keyword.
  • Once defined, their value cannot be changed.
  • By convention, constant names are uppercase.
<?php
define("SITE_NAME", "My Awesome Site");
const MAX_USERS = 1000;

echo SITE_NAME;
echo MAX_USERS;
?>

Data Types

PHP supports several primitive and compound data types.

Scalar Types

  • Integer: Whole numbers (e.g., 10, -5, 0x1A).
  • Float (Double): Numbers with decimal points (e.g., 3.14, 2.0).
  • String: Sequence of characters enclosed in single (') or double (") quotes. Double quotes allow variable interpolation.
  • Boolean: true or false (case-insensitive).
<?php
$int_var = 123;
$float_var = 12.34;
$string_var = "Hello, PHP!";
$bool_var = true;

echo gettype($int_var);    // Output: integer
echo gettype($string_var); // Output: string
echo "The value of bool_var is: " . ($bool_var ? "true" : "false");
?>

Compound Types

  • Array: Ordered map. Can hold values of different types.
  • Object: Instances of classes.
<?php
$my_array = [1, "two", true]; // Indexed array
$user = ["name" => "John", "age" => 30]; // Associative array

class Person {
    public $name;
    function __construct($name) {
        $this->name = $name;
    }
}
$person_obj = new Person("Jane");
?>

Special Types

  • NULL: A variable with no value, or explicitly assigned NULL.
  • Resource: Special variables holding references to external resources (e.g., database connections, file handles).
<?php
$null_var = null;
echo is_null($null_var); // Output: 1 (true)
?>

2. Operators

Operators are used to perform operations on variables and values.

Web3 Fellowship Programs: Top Opportunities for Developers

Master Writing Scholarship Essays: Winning Templates and Expert Tips

10 Best Webinar Platforms in February 2026 [Free+Paid]

Arithmetic Operators

Used for mathematical calculations.

Operator Description Example Result
+ Addition $x = 10 + 5; 15
- Subtraction $x = 10 - 5; 5
Multiplication $x = 10 5; 50
/ Division $x = 10 / 5; 2
% Modulus $x = 10 % 3; 1
Exponentiation $x = 2 3; 8

Assignment Operators

Used to assign values to variables.

- Advertisement -
Operator Example Equivalent To
= $x = 10; $x = 10;
+= $x += 5; $x = $x + 5;
-= $x -= 5; $x = $x - 5;
= $x = 5; $x = $x 5;
/= $x /= 5; $x = $x / 5;
%= $x %= 3; $x = $x % 3;
. $str .= "hi"; $str = $str . "hi";

Comparison Operators

Used to compare two values. They return a boolean true or false.

Operator Description Example Result
== Equal (value) 10 == "10" true
=== Identical (value & type) 10 === "10" false
!= Not equal (value) 10 != 5 true
!== Not identical 10 !== "10" true
< Less than 5 < 10 true
> Greater than 10 > 5 true
<= Less than or equal to 10 <= 10 true
>= Greater than or equal to 10 >= 5 true
<=> Spaceship (PHP 7+) 1 <=> 2 (-1), 2 <=> 1 (1), 1 <=> 1 (0)

Logical Operators

Used to combine conditional statements.

Operator Description Example Result
&& And $a && $b (both true) true
` ` Or
! Not !$a (inverts boolean value) true

Increment/Decrement Operators

Used to increase or decrease a variable’s value by one.

Operator Description Example
++$x Pre-increment Increments $x by one, then returns $x.
$x++ Post-increment Returns $x, then increments $x by one.
--$x Pre-decrement Decrements $x by one, then returns $x.
$x-- Post-decrement Returns $x, then decrements $x by one.

String Operator

  • .: Concatenation (joins two strings).
<?php
$greeting = "Hello" . " " . "World!"; // "Hello World!"
?>

Ternary Operator

A shorthand for if...else statements.

<?php
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor"; // Output: Adult
?>

Null Coalescing Operator (??, PHP 7+)

Returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.

<?php
$username = $_GET['user'] ?? 'Guest'; // If $_GET['user'] is not set or is null, $username becomes 'Guest'
?>

3. Control Flow

Control flow statements allow you to execute code conditionally or repeatedly.

Conditional Statements

if, else if, else

Executes different blocks of code based on conditions.

<?php
$score = 85;

if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 80) {
    echo "Grade: B";
} else {
    echo "Grade: C or lower";
}
?>

switch

Executes different blocks of code based on the value of a single variable.

<?php
$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Start of the week.";
        break;
    case "Friday":
        echo "End of the week!";
        break;
    default:
        echo "Mid-week day.";
}
?>

Loops

for Loop

Repeats a block of code a specified number of times.

<?php
for ($i = 0; $i < 5; $i++) {
    echo "Iteration " . $i . "<br>";
}
?>

foreach Loop

Iterates over elements in an array or object.

<?php
$colors = ["red", "green", "blue"];

foreach ($colors as $color) {
    echo $color . "<br>";
}

$user = ["name" => "Alice", "age" => 25];
foreach ($user as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>

while Loop

Repeats a block of code as long as a specified condition is true.

<?php
$count = 0;
while ($count < 3) {
    echo "Count: " . $count . "<br>";
    $count++;
}
?>

do-while Loop

Similar to while, but the block is executed at least once before the condition is checked.

<?php
$i = 0;
do {
    echo "The number is: " . $i . "<br>";
    $i++;
} while ($i < 5);
?>

break and continue

  • break: Terminates the current loop or switch statement.
  • continue: Skips the rest of the current loop iteration and proceeds to the next iteration.
<?php
for ($i = 0; $i < 10; $i++) {
    if ($i == 3) {
        continue; // Skip 3
    }
    if ($i == 7) {
        break;    // Stop at 7
    }
    echo $i . " "; // Output: 0 1 2 4 5 6
}
?>

4. Functions

Functions are blocks of code designed to perform a specific task.

Defining and Calling Functions

<?php
function greet($name) {
    return "Hello, " . $name . "!";
}

echo greet("World"); // Output: Hello, World!
?>

Parameters and Return Types

  • Default Parameters: Assign default values to parameters.
  • Type Declarations (PHP 7+): Specify expected data types for parameters and return values.
<?php
function add(int $a, int $b = 0): int {
    return $a + $b;
}

echo add(5);     // Output: 5 (b defaults to 0)
echo add(5, 3);  // Output: 8
?>

Anonymous Functions (Closures)

Functions without a name, often used as callbacks.

<?php
$numbers = [1, 2, 3, 4];
$squared_numbers = array_map(function($n) {
    return $n  $n;
}, $numbers);

print_r($squared_numbers); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
?>

Arrow Functions (fn, PHP 7.4+)

A more concise syntax for anonymous functions with a single expression.

<?php
$factor = 2;
$multiply = fn($num) => $num * $factor;

echo $multiply(5); // Output: 10
?>

5. Arrays

Arrays are ordered maps that can store multiple values in a single variable.

Indexed Arrays

Elements are accessed using numeric indices (starting from 0).

<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Output: apple

$fruits[] = "date"; // Add to the end
print_r($fruits); // Output: Array ( [0] => apple [1] => banana [2] => cherry [3] => date )
?>

Associative Arrays

Elements are accessed using named keys.

<?php
$person = [
    "name" => "Jane Doe",
    "age" => 30,
    "city" => "New York"
];
echo $person["name"]; // Output: Jane Doe

$person["occupation"] = "Developer"; // Add new key-value pair
print_r($person);
?>

Multidimensional Arrays

Arrays containing other arrays.

<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
echo $matrix[1][2]; // Output: 6
?>

Common Array Functions

  • count($array): Returns the number of elements.
  • array_push($array, $value1, ...): Pushes one or more elements onto the end of an array.
  • array_pop($array): Pops the last element off the end of an array.
  • array_merge($array1, $array2, ...): Merges one or more arrays.
  • in_array($needle, $haystack): Checks if a value exists in an array.
  • array_keys($array): Returns all the keys of an array.
  • array_values($array): Returns all the values of an array.
  • sort($array): Sorts an indexed array in ascending order.
  • rsort($array): Sorts an indexed array in descending order.
  • asort($array): Sorts an associative array by value in ascending order.
  • ksort($array): Sorts an associative array by key in ascending order.
  • array_map($callback, $array): Applies a callback function to the elements of the given arrays.
  • array_filter($array, $callback): Filters elements of an array using a callback function.
  • array_reduce($ (Note: MAX_TOKENS)array, $callback, $initial): Iteratively reduce

You Might Also Like

Remote Web3 Developer Salaries: 2026 Compensation Trends & Expectations
How Nigeria can use crypto companies to its advantage
Required Documents for Duns & Bradstreet: Essential List for Businesses
5G Quietly Reshaping Mobile Gaming Rules Today
Last Mile Delivery: 7 Proven Ways to Solve Costly Challenges
TAGGED:learn PHPmodern PHPPHP cheatsheetPHP developmentPHP for developersPHP fundamentalsPHP guidePHP programmingPHP quick referencePHP syntax
Share This Article
Facebook Whatsapp Whatsapp Copy Link Print
Previous Article Web3 Fellowship Programs Web3 Fellowship Programs: Top Opportunities for Developers
Next Article PHP Variables and Datatypes Learn PHP Variables and Datatypes: A Quick Start Guide
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Prove your humanity: 0   +   4   =  

Latest News

Fitbit Charge 7 may launch soon, as Fitbit Edge
Fitbit Charge 7 May Launch Soon as Fitbit Edge Smartwatch
Phones Review
SEO Content Roadmap for AI Search: Step-by-Step Guide
SEO Content Roadmap for AI Search: Step-by-Step Guide
Web Technologies
AI User-Agents: Complete List of Web Crawlers
AI User-Agents: Complete List of Web Crawlers (Sep 2026)
Web Technologies
Card Not Present fraud
Card Not Present fraud: Causes, Impacts & Prevention of CNP Fraud
Web Technologies
Online Fraud Detection
Online Fraud Detection: How Businesses Spot Suspicious Activity
Web Technologies
Googlebot Tops AI
Googlebot Tops AI Crawler Traffic: Cloudflare Report Confirms Dominance
Web Technologies
Prevent Bots from Crawling Admin Areas and Private Content
Prevent Bots from Crawling Admin Areas and Private Content
Web Technologies
What is PetalBot? Good or Bad for Your Website SEO?
What is PetalBot? Good or Bad for Your Website SEO?
Web Technologies

You Might also Like

Nigerian passport
general post

5 Asian Countries Offering Easy Visas for Nigerians

Faisal Salisu
By Faisal Salisu
4 Min Read
android studio
general post

How to Install Android Studio on Ubuntu?

Faisal Salisu
By Faisal Salisu
9 Min Read
AI Research Fellowships
general post

How to Apply and WinTop AI Research Fellowships in 2026/2027

Faisal Salisu
By Faisal Salisu
19 Min Read
//

Slamari is a global Web3, AI and technology careers platform connecting professionals with emerging opportunities, jobs, skills, startups, and innovations shaping the future of work.

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

[mc4wp_form id=”1616″]

SlamariSlamari
Follow US
© 2022 slamari global tech. All Rights Reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?