DEV Community

David Kanekanian
David Kanekanian

Posted on

PHP Language Basics

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

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.
// 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;
Enter fullscreen mode Exit fullscreen mode

Annotation

  • Lets you write comments around your code explaining it.
  • Won't be executed by the computer.
  • Useful for temporarily disabling a section of code.
// Single line comments
# Single line comments
/* Multi line
Comment */
Enter fullscreen mode Exit fullscreen mode

Variables

  • 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.
$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
Enter fullscreen mode Exit fullscreen mode

Constants

  • 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.
// 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...
}
Enter fullscreen mode Exit fullscreen mode

Selection

  • 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.
// 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";
Enter fullscreen mode Exit fullscreen mode

Iteration

  • Available loops are: for, while, do while and foreach.
  • See examples for how to use them.
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...
}
Enter fullscreen mode Exit fullscreen mode

Functions

  • 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.
// 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);
Enter fullscreen mode Exit fullscreen mode

Strings

  • 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
// 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"
Enter fullscreen mode Exit fullscreen mode

Communicating Data

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

Top comments (0)