DEV Community

Cover image for PHP Syntax Cheatsheet [Part 1]
Adnan Babakan (he/him)
Adnan Babakan (he/him)

Posted on

PHP Syntax Cheatsheet [Part 1]

Hey there DEV.to community!

Here I am compiling a list of PHP syntax cheatsheet for you all. As for why I am writing this post, PHP was my first programming language, and I still feel like I am in love with it, and it deserves more attention. Thus, trying to spread PHP knowledge for those learning it for the first time or trying to get back to it.

In this part I will go through basic PHP syntax and in the next part I will discuss the OOP aspect much more in detail.

Table of Content

Syntax

PHP files are named with .php extension and start with <?php or <? and end with ?>. It is good to not that ending tag is not mandatory if you whole file consists of PHP and no HTML afterwards.

<?php
// CODE GOES HERE
?>
Enter fullscreen mode Exit fullscreen mode

Or simply:

<?php
// CODE GOES HERE
Enter fullscreen mode Exit fullscreen mode

Comments

As for every programming language you need comments to describe your code. PHP provides multiple ways to comment.

<?php
// THIS IS A COMMENT
# THIS IS A COMMENT AS WELL
/*
AND THIS IS
A MULTI-LINE COMMENT
*/
Enter fullscreen mode Exit fullscreen mode

Using // and #, you may create a single-line comment. And by putting you comment between /* and */ you can create a multi-line comment.

Variables

Variables in PHP are defined using $ followed by their name. A variable in PHP isn't typed and can hold any value that PHP offers. A variables value can be changed later on.

<?php
$i = 1;
$name = 'Adnan';
Enter fullscreen mode Exit fullscreen mode

It is good to know that PHP statements require a semicolon at the end, and it is not optional.

Variable variables

While it is against the convention, since variables are defined using $, it is possible to define a variable's name using another variable.

<?php
$v = 'test';
$$v = 'HELLO WORLD';
echo $test; // HELLO WORLD
Enter fullscreen mode Exit fullscreen mode

I am not encouraging using such an approach, but it is possible, so mentioning it here is an honourable mention.

Constant

A constant is almost like a variable but its value can only be declared once and later on it cannot be changed. By convention constant names are defined in UPPER_SNAKE_CASE.

Run-time constant

A runtime constant can be defined using the define() function.

<?php
define(MY_CONST, 'HELLO');
echo MY_CONST; // HELLO
Enter fullscreen mode Exit fullscreen mode

Compile-time constant

A compile-time constant can be defined using the const keyword.

<?php
const MY_CONST = 'HELLO';
echo MY_CONST; // HELLO
Enter fullscreen mode Exit fullscreen mode

Types

PHP is a dynamically-typed language, which means you don't need to declare every type you use, yet it is essential to know what you are passing around as values so you can control how it affects your program.

String

A string is a series of characters, such as a name or a full sentence. A PHP string can be defined between quotes ' and double-quotes ".

<?php
$name = 'Adnan';
$last_name = 'Babakan';
Enter fullscreen mode Exit fullscreen mode

The difference between a single quote and a double quote is simple. Inside a single-quote, wrap everything is considered literal and will remain as is. But inside a double-quote, variables are evaluated, and their values are placed in the string.

<?php
$name = 'Adnan';
$test1 = 'Hi I am $name'; // Hi I am $name
$test2 = "Hi I am $name"; // Hi I am Adnan
Enter fullscreen mode Exit fullscreen mode

For best practices, it is good to use single quotes and not double quotes, as it can result in unwanted behaviour.

Integer

Integers or simple int is a whole number without a decimal point.

<?php
$i = 2;
$j = 10;
Enter fullscreen mode Exit fullscreen mode

Float

Floating point numbers (one of the most controversial features in programming languages) is a number with a decimal point.

<?php
$pi = 3.14;
$k = 7.98;
Enter fullscreen mode Exit fullscreen mode

Boolean

A boolean or a bool is simply a value of true or false. They are used in conditions and many places to switch between two different actions. Later on we will discuss comparison operators, which will result in a boolean.

<?php
$k1 = true;
$k2 = false;
Enter fullscreen mode Exit fullscreen mode

Remember that true and 'true' and respectively false and 'false' are two different things. If you put them inside a quotation or double quotation they are considered a string and not a boolean. Just like a simple text.

Array

An array is a series of values that can be accessed using their index or pre-defined keys. So we will separate arrays in PHP into two different categories: Index-based and key-value arrays.

Index-based array

An index-based array is simply wrapped with [ and ] and each element is separated with a comma. Values (elements) of an array in PHP can be of any type and they don't have to be the same.

<?php
$a1 = ['Hello', 2, true, 3.14];
Enter fullscreen mode Exit fullscreen mode

In order to access an element here is how we do it:

<?php
$a1 = ['Hello', 2, true, 3.14];
echo $a1[0]; // 'Hello'
echo $a1[1]; // 2
echo $a1[2]; // true
echo $a1[3]; // 3.14
Enter fullscreen mode Exit fullscreen mode

Remember that indices start from 0 in PHP and not 1. (There is a logical reason behind it but it is beyond the scope of this post. Yet you can research for yourself why it starts from 0.)

Key-based array

A key based array is defined differently. Each key-value pair is define using key => value syntax and separated by a comma again.

<?php
$a2 = [
    'name' => 'Adnan',
    'age'  => 25
];
Enter fullscreen mode Exit fullscreen mode

And in order to access the value we do the same, but this time instead of an index we provide the defined key:

<?php
$a2 = [
    'name' => 'Adnan',
    'age'  => 25
];
echo $a2['name']; // Adnan
echo $a2['age']; // 25
Enter fullscreen mode Exit fullscreen mode

It is good to know that most keys are strings but the values can be of any type again.

Array language construct

It is possible to define both index-based and key-based arrays using a function-like construct named array(). What we had learnt before is just a short form for this constrcut.

<?php
$a1 = array('Hello', 2, true, 3.14);
$a2 = array(
    'name' => 'Adnan',
    'age'  => 25
);
Enter fullscreen mode Exit fullscreen mode

Multi-dimensional arrays

Arrays can hold arrays and that is what we call a multi-dimensional array.
Here is a simple one:

<?php
$m = [[1,2,3], [4,5,6], [7,8,9]];
echo $m[0][0]; // 1
echo $m[1][2]; // 6
echo $m[2][1]; // 8
Enter fullscreen mode Exit fullscreen mode

It is good to note that a key-based array can be multi-dimensional as well:

<?php
$o = [
    'friends' => ['Arian', 'Ata', 'Mahdi', 'Erfan'],
];
echo $o['friends'][1]; // Ata
Enter fullscreen mode Exit fullscreen mode

Null

Null is a special value that means nothing.

<?php
$n = null;
Enter fullscreen mode Exit fullscreen mode

And that's it. While being simple you will see so many uses of this special value.

Echo and Print

echo() and print() are most used functions to print something to the standard output. Being a web client or simply terminal.
You can use echo and print without parentheses.

<?php
echo 'Hello World';
print 'How are you doing?';
Enter fullscreen mode Exit fullscreen mode

Casting

Casting means converting one data type to another. For instance converting a number to a string or vice-versa. Not all data types can be converted to each other. The simple rule is that it has to make sense. (I know this is vague but consider it suffecient for now :) ).

To cast a value to another type simply put the targeted type inside parentheses and before the source value:

<?php
$a = (string) 2;
gettype($a); // string
Enter fullscreen mode Exit fullscreen mode

gettype() is a function that returns the data type of the variable.

The list of castings are as below:

  • (string)
  • (int)
  • (float)
  • (bool)
  • (array)
  • (object)

If you are not seeing object in the types section above, you are completely right. Objects are more elaborate and will be discussed later in this post.

Operators

Operators are used for multiple purposes, such as arithmetic (mathematical) or comparison reasons. Here are full list of PHP operators.

Arithmetic operators

Arithmetic operatos are used for summation, division and etc. Here is the full list:

+ Summation

<?php
$n = 8 + 7; // 15
Enter fullscreen mode Exit fullscreen mode

- Subtraction

<?php
$n = 10 - 3; // 7
Enter fullscreen mode Exit fullscreen mode

* Multiplication

<?php
$n = 2 * 4; // 8
Enter fullscreen mode Exit fullscreen mode

/ Division

<?php
$n = 10 / 2; // 5
Enter fullscreen mode Exit fullscreen mode

** Exponentiation

<?php
$n = 2 ** 3; // 8
Enter fullscreen mode Exit fullscreen mode

% Modulo

This operator is used for getting the remainder of a number divided by another.

<?php
$n = 9 % 4; // 1
Enter fullscreen mode Exit fullscreen mode

Comparison operators

Comparison operators are used to compare two values and result in a boolean. They are used in conditions to evaluate a result.

== equal and !=/<> not equal

Check if two values are equal/ not equal independant of their types.

<?php
$n = "2" == 2; // true
$k = 3 == 3; // true
$o = 4 == "hello"; // false
$h = 6 != "6"; // false
$e = 6 != 5; // true
Enter fullscreen mode Exit fullscreen mode

You can use <> operator instead of the != operator as well.

=== identical and !== not identical

<?php
$n = "2" === 2; // false
$k = 3 === 3; // true
$o = 4 === "hello"; // false
$h = 6 !== "6"; // true
$e = 6 !== 5; // true
Enter fullscreen mode Exit fullscreen mode

< less than and <= less than or equal

<?php
$a = 2 < 3; // true
$b = 3 < 1; // false
$c = 4 <= 4; // true
Enter fullscreen mode Exit fullscreen mode

> greater than and >= greater than or equal

<?php
$a = 4 > 1; // true
$b = 5 > 6; // false
$c = 9 >= 9; // true
Enter fullscreen mode Exit fullscreen mode

<=> Spaceship operator

If the value on the left-hand side is less than the one on the right-hand side the result is equal to -1. If they are equal the result is equal to 0 and if the left-hand side is greater than on the right-hand side the result is equal to 1.

<?php
$a = 4 <=> 5; // -1
$b = 5 <=>; // 0
$c = 6 <=> 2; // 1
Enter fullscreen mode Exit fullscreen mode

Conditions

A condition is a flow-control statement that determines if a block should be run or not, and if not any other blocks will proceed in case it is defined to do so.

If

An if statement is simply defined as below:

<?php
if (condition) {
    // CODE GOES HERE
}
Enter fullscreen mode Exit fullscreen mode

In place of the work condition there should be a boolean or a comparison that results in a boolean. If the boolean evaluates to true then the code inside two curly-braces ({ and }) run.

If-else and elseif

An else statement is defined immediately after an if statement and the code inside its block is run in case the condition for if evaluates to false:

<?php
if (condition) {
    // CODE GOES HERE
} else {
    // CODE GOES HERE
}
Enter fullscreen mode Exit fullscreen mode

You may also define multiple elseif statements between if and else to check other conditions:

<?php
if(condition) {
    // CODE GOES HERE
} elseif (condition2) {
    // CODE GOES HERE
} elseif (condition3) {
    // CODE GOES HERE
} else {
    // CODE GOES HERE
}
Enter fullscreen mode Exit fullscreen mode

Switch case

A switch case checks the value provided to it to be equal to any of its cases, and if not, the default case is triggered. It is kind of like a chained if-elseif-else statement, but only checking for equality.

<?php
$fruit = 'apple';
switch($fruit) {
    case 'banana':
        echo 'yellow';
    break;
    case 'apple':
        echo 'red';
    break;
    case 'cucumber':
        echo 'green';
    break;
    default:
        echo 'NOT FOUND';
    break;
}
Enter fullscreen mode Exit fullscreen mode

The code above will echo the word red as $fruit is equal to apple. After each case, there needs to be a break statement to break the switch block. The last case/default case doesn't require a break, but I always include it just for the sake of consistency.

Loops

As one of my professors once said, a loop statement is the most important statement in programming, as it runs a block of code multiple times. If computers were only to do a thing once, then there would be no need for them.

For loop

A for loop consists of three parts usually, an initilization, a condition and a mutator.

<?php
for($i = 0; $i < 10; $i++) {
    // CODE HERE RUNS FOR 10 TIMES, FROM 0 to 9.
}
Enter fullscreen mode Exit fullscreen mode

While loop

A while loop only consists of a condition and checks if the condition is true and runs the code block if so.

<?php
while(true) {
    // CODE HERE RUNS FOREVER
}
Enter fullscreen mode Exit fullscreen mode

You may recreate a for loop using a while loop as below:

<?php
$i = 0;
while($i < 10) {
    // CODE HERE RUNS FOR 10 TIMES, FROM 0 to 9.
    $i++;
}
Enter fullscreen mode Exit fullscreen mode

Do while loop

A do while loop runs almost like a while loop with one difference. It runs at least once since it checks the condition afterwards and not at the beginnign.

<?php
do {
    // CODE HERE RUNS ONCE AND THEN CHECKS THE CONDITION WHICH IS FALSE
} while (false);
Enter fullscreen mode Exit fullscreen mode

Foreach loop

A for each loop iterates through a array.

Here is the sample for an index based array:

<?php
$a = [10, 20, 30];
foreach($a as $el) {

}
Enter fullscreen mode Exit fullscreen mode

Inside the loop you may access the $el variable which is equal to each memeber of the array in each iteration.

And here is an example for a key-value array:

<?php
$k = [
    "a" => 10,
    "b" => 20,
    "c" => 30
];
foreach($k as $key => $value) {

}
Enter fullscreen mode Exit fullscreen mode

In each iteration, you may access $key and $value variables, which correspond to each key and value in the array.

It is good to know that in both foreach loops demonstrated above, the names $el, $key and $value are arbitrary and can be any valid variable name you desire.

Functions

A function is a block of code that can be reused, have arguments and return a value as well.

A function in PHP is defined as below:

<?php
function sum($a, $b) {
    return $a + $b;
}

echo sum(10, 20); // 30
Enter fullscreen mode Exit fullscreen mode

In the next chapter we will discuss OOP aspect of PHP and then in the later chapter the more advanced tricks of PHP are going to be included.


BTW! Check out my free Node.js Essentials E-book here:

Feel free to contact me if you have any questions, projects or suggestions to improve this article.

Top comments (1)

Collapse
 
f4telord profile image
Arian Amini

Great work keep it up!