PHP Language Basics
Tags: php, tutorial
Published: 2020-04-14 13:44:57

This post will detail the rules of PHP with code examples for each. In later posts, we will dive into how to use these features with examples. You can also use this post for future reference.

## Table Of Contents
* [Syntax](#syntax)
* [Annotation](#annotation)
* [Variables](#variables)
* [Constants](#constants)
* [Selection](#selection)
* [Iteration](#iteration)
* [Functions](#functions)
* [Strings](#strings)
* [Communicating Data](#communicating-data)

## Syntax <a name="syntax"></a>
Here are the basic rules to follow:
* Needs `;` semicolon after statements (usually the end of each line). This means you can put multiple statements on one line, but it’s not recommended.
```php
// Examples of valid statements:
functionCall();
$assignment = "david";
$math = 2 + 2;
2 + 2;  // Valid statement, but won't store the result anywhere!

// You can write multiple short statements on one line, but it may
// be clearer to use new lines for longer names.
$a=1; $b=2; $c=3;
```

### Annotation <a name="annotation"></a>
* Lets you write comments around your code explaining it.
* Won't be executed by the computer.
* Useful for temporarily disabling a section of code.
```php
// Single line comments
# Single line comments
/* Multi line
Comment */
```

### Variables <a name="variables"></a>
* Variables start with a `$` dollar sign.
* Values are similar to Python, but instead of None there is `NULL`.
* Arrays are like Python lists (values don’t have to be the same type).
* Associative arrays are like Python dictionaries, but use square brackets and have `=>` between each key and its value.
```php
$myString = "hello"; // String - letters
$myInt = 2; // Integer - whole numbers
$myFloat = 2.0; // Float - real numbers
$myNull = NULL; // Null - holds nothing
$myBool = true; // Boolean - true or false
$myArray = ["value1", "value2", "value3"]; // Array - accessed by position starting from 0
$myAssociativeArray = ["key1" => "value1", "key2" => "value2"]; // Associative Array - accessed by key
```

### Constants <a name="constants"></a>
* Useful for defining values that shouldn't be changed.
* Commonly named using all capital letters and without a dollar sign.
* Can have almost any value variables can - even arrays.
* Can be defined in global scope or in a class.
```php
// Global constant:
define("MY_CONSTANT", "this value can't be changed afterwards");
// Usage:
if ($a == MY_CONSTANT) {
    # code...
}
 
// Class constant:
class MyClass
{
    const MY_CONSTANT = "hello";
}
// Usage:
if ($a == MyClass::MY_CONSTANT) {
    # code...
}
```

### Selection <a name="selection"></a>
* Condition must be enclosed in `()` parentheses and body must be enclosed in `{}` curly braces.
* If the body isn’t enclosed in curly braces, only the very next statement is the body.
```php
// If, elseif, else block.
if ($a < 10) {
    # code...
} else if ($a < 20) {
    # code...
} else {
    # code...
}
 
// If statement without curly braces.
if ($a < 10) echo "condition met";
echo "outside if statement - always executed";
 
 
// Switch statement - compares a variable to the available options.
switch ($variable) {
case "option1":
    # code...
    break;
case "option2":
    # code...
    break;
default:
    # code...
    break;
}

 
// If $a is less than 10, $b is used. Otherwise $c is used.
$d = ($a < 10) ? $b : $c;
 
// "default" is used if myArray doesn't contain "key2".
$value = $myArray["key2"] ?? "default";
```

### Iteration <a name="iteration"></a>
* Available loops are: `for`, `while`, `do while` and `foreach`.
* See examples for how to use them.

```php
for ($i=0; $i < 10; $i++) { 
    # code...
}
 
while ($a <= 10) {
    # code...
}
 
do {
    # code...
} while ($a <= 10);
 
foreach ($myArray as $item) {
    # code...
}
 
foreach ($myAssociativeArray as $key => $value) {
    # code...
}
```

### Functions <a name="functions"></a>
* Defined by function instead of Python’s `def`.
* Body must be enclosed by `{}` curly braces.
* Function name is optional, but usually necessary.
* Can have multiple parameters with default values and a single return value, optionally with types specified.
```php
// Declare a function with parameters and a return value.
function myFunction($arg1, $arg2, $arg3 = "default value")
{
    # code...
    return true;
}
 
// Optionally specify the parameter and return types for extra clarity.
function myFunction2(int $arg1, float $arg2, string $arg3 = "default value"): bool
{
    # code...
    return true;
}
 
// Calling a function.
$returnValue = myFunction(1, 2.0);
```

### Strings <a name="strings"></a>
* Can be declared with `'` single or `"` double quotes
* Concatenated with a `.` dot.
* Variables can be substituted into a literal string with a dollar sign
* Variable substitution will only work for double quotes
```php
// Declaring a literal string.
$string1 = "hello";
// Concatenating strings.
$string2 = $string1 . " world"; // "hello world"
// Substituting variable into literal string.
// Some IDE's may highlight the variable differently!
$string3 = "$string1 world"; // "hello world"
// Substituting variable by accessing items from arrays.
$myArray = ["key1" => "hello", "key2" => "world"];
$string4 = "$myArray[key1] $myArray[key2]"; // "hello world"
// Formatting strings.
$string5 = sprintf("%s world", $string1); // "hello world"
```

## Communicating Data <a name="communicating-data"></a>
There are several ways to send data from one PHP script to another.
* **Get/Post** - mainly from user interaction
* **Cookie** - specific to each user’s computer
* **Session** - like cookie but internally stored on server
* **Database** - more permanent data storage