PHP Basics by Dario Evaristo Bellotta

PHP Basics by Dario Evaristo Bellotta

This PHP Basics Guide covers only the essential fundamentals, designed to be revisited multiple times to solidify your understanding of the basics. Follow me on Instagram @darioevaristobellotta

5 Getting started Information:

  • PHP needs a webserver like xampp
  • PHP files end with .php
  • File starts with <?php
  • PHP runs top to bottom
  • Statements end with semicolon ;

Constants and Variables:

Variables can be overwritten

$firstName = "Dario";

$firstName = "Mario";

echo $firstName;
// prints Mario

Constants can not be overwritten (this wouldn’t work)

const NAME = "Dario";

NAME = "Mario";

echo NAME;
// always Dario or Error

or define it with:

define("NAME", "Dario");

echo NAME;
// prints Dario

Data Types 1 4 Scalar Types:

boolean (true or false)

$dario = true;
$notDario = false;

var_dump($dario);
// prints bool(true)

integer (no decimal)

$myAge = 32;

var_dump($myAge);
// prints int(32)

float (decimal)

$myExactAge = 32.5;

var_dump($myExactAge);
// prints float(32.5)

string (words, letters)

$firstName = “Dario”;

var_dump($firstName);
// prints string(5) “Dario”

Data Types 2 Compound Types Arrays 1:

array (list of values)

$myArray = [1, 5.1, -9, “Dario”, true];

print_r($myArray);
// prints all values
  • When you notice a repetition in your code (your variables) you need to structure your data differently like arrays.

echo arrays

$myArray = [1, 5.1, -9, “Dario”, true];

echo $myArray[0];
// prints 1

echo $myArray[1];
// prints 5.1

check if key exists

$myArray = [1, 5.1, -9, "Dario", true];

var_dump(isset($myArray[0]));
// prints bool(true)

overwrite value

$myArray = [1, 5.1, -9, "Dario", true];

$myArray[0] = 2;

echo $myArray[0];
// prints 2 not 1

print in pretty

$myArray = [1, 5.1, -9, "Dario", true];

echo "<pre>";
print_r($myArray);
echo "</pre>";
// prints it pretty

push to end of array

$myArray = [1, 5.1, -9, "Dario", true];

$myArray[] = "new";
// adds it to end of array

push to end of array 2

$myArray = [1, 5.1, -9, "Dario", true];

array_push($myArray, "new");
// adds it to end of array

delete from first index

$myArray = [1, 5.1, -9, "Dario", true];

array_shift($myArray);
// removes 1 at index 0

unset from index

$myArray = [1, 5.1, -9, "Dario", true];

unset($myArray[2]);

print_r($myArray);
// prints without -9

unset entire array

$myArray = [1, 5.1, -9, "Dario", true];

unset($myArray);

print_r($myArray);
// prints warning undefined

Data Types 2 Compound Types Arrays 2:

associative array

$myArray = [
  "name" => "Dario",
  "age" => 32
];

print_r($myArray);
// prints all values and keys

echo associative arrays

$myArray = [
  "name" => "Dario",
  "age" => 32
];

echo $myArray["name"];
// prints Dario
  • Associative arrays are arrays that use named keys that you assign to them
  • They are like JavaScript Objects

multidimensional array

$myArray = [
  "name" => [
      "firstName" => "Dario",
      "secondName" => "Evaristo",
      "sureName" => "Bellotta"
       ],
  "age" => 32
];

print_r($myArray);
// prints all values and keys

echo multidimensional arrays

$myArray = [
  “name” => [
      “firstName => “Dario”,
      “secondName” => “Evaristo”,
      “sureName” => “Bellotta”
       ],
  “age” => 32
};

echo $myArray[”name”][”firstName”];
// prints Dario

Data Types 4 Null:

null (absence of a value)

$x = null;

var_dump($x);

// prints NULL
  • null has only one value: null
  • undefined or unset() variables will resolve to null
  • if you dont know a value of a variable yet you can assign it to null

Operators 1 Arithmetic:

Addition

$x = 10;
$y = 2;

var_dump($x + $y);
// prints int(12)

Subtraction

$x = 10;
$y = 2;

var_dump($x - $y);
// prints int(8)

Multiplication

$x = 10;
$y = 2;

var_dump($x * $y);
// prints int(20)

Division

$x = 10;
$y = 2;

var_dump($x / $y);
// prints int(5)

Modulo

$x = 10;
$y = 3;

var_dump($x % $y);
// prints int(1)

Exponentiation

$x = 10;
$y = 2;

var_dump($x ** $y);
// prints int(100)

Operators 2 Assignment:

Normal Assignment

$x = 10;

// assigns 10 to $x

Arithmetic Assignment

$x = 10;

$x += 2 // $x is 12
$x -= 2 // $x is 8
$x *= 2 // $x is 20
$x /= 2 // $x is 5
$x %= 2 // $x is 0
$x **= 2 // $x is 100

Operators 3 String:

concatenation operator

$x = "Hello";
$x = $x . " World";

echo $x;
// prints Hello World

concatenation assignment

$x = "Hello";
$x .= " World";

echo $x;
// prints Hello World

Operators 4 Comparison:

loose comparison (equal)

$x = 5;
$y = "5";

var_dump($x == $y);
// prints bool(true)

strict comparison (Identical)

$x = 5;
$y = "5";

var_dump($x === $y);
// prints bool(false)

loose comparison (not equal)

$x = 5;
$y = "5";

var_dump($x != $y);
var_dump($x <> $y);
// prints both bool(false)

strict comparison (not Identical)

$x = 5;
$y = "5";

var_dump($x !== $y);
// prints bool(true)

greater and less than

$x = 5;
$y = 3;

var_dump($x > $y);
// prints bool(true)

var_dump($x < $y);
// prints bool(false)

greater and less than or equal

$x = 5;
$y = 5;

var_dump($x >= $y);
// prints bool(true)

var_dump($x <= $y);
// prints bool(true)

spaceship

$x = 5;
$y = 10;
var_dump($x <=> $y);
// prints int(-1)

$x = 10;
$y = 10;
var_dump($x <=> $y);
// prints int(0)

$x = 15;
$y = 10;
var_dump($x <=> $y);
// prints int(1)

Operators 5 Conditional:

Ternary operator (?:)

$x = true;

$result = $x === true ? "Result true" : "Result false";

echo $result
// prints Result true

Ternary operator (?:) 2

$x = false;

$result = $x === true ? "Result true" : "Result false";

echo $result
// prints Result false
  • The ternary operator checks if an expression is true or not just like an if statement.

Null coalescing (??)

$x = null;

$y = $x ?? "hello";

var_dump($y);
// prints string(5) "hello"

Null coalescing (??) 2

$x = false;

$y = $x ?? "hello";

var_dump($y);
// prints bool(false)
  • The Null coalescing operator checks if a variable is null or not and returns either the expression or the value of the variable if it’s not null.

Operators 6 In- / Decrement:

Pre-increment

$x = 5;

echo ++$x;
// prints 6

Post-increment

$x = 5;

echo $x++;
// prints 5 increases after

Pre-decrement

$x = 5;

echo --$x;
// prints 4

Post-decrement

$x = 5;

echo $x--;
// prints 5 decreases after

Operators 7 Logical:

And operator

$x = true;
$y = true;

var_dump($x && $y);
// prints bool(true)

And operator 2

$x = true;
$y = true;

var_dump($x and $y);
// prints bool(true)

Or operator

$x = true;
$y = false;

var_dump($x || $y);
// prints bool(true)

Or operator 2

$x = true;
$y = false;

var_dump($x or $y);
// prints bool(true)
  • Use the symbol operator (&& ||) instead of (and or) because the word operator has a lower precedence and can get you wrong results.

Not or negation operator

$x = false;
$y = false;

var_dump(!$x || $y);
// prints bool(true)

xor operator

$x = true;
$y = false;

var_dump($x xor $y);
// prints bool(true)
  • Xor operator is true if either $x or $y is true, bot not both.

Operators 8 Array:

Union operator

$x = ["a", "b"];
$y = ["c", "d", "f"];

$z = $x + $y;
print_r($z);

// prints Array ([0] => a [1] => b [2] => f)
  • Union operator appends to the array if it doesn’t exist at the same index.

comparison operator

$x = [1, 2, 3];
$y = [1, "2", 3];

var_dump($x == $y);
// prints bool(true)

Strict comparison operator

$x = [1, 2, 3];
$y = [1, "2", 3];

var_dump($x === $y);
// prints bool(false)
  • Comparison operator will be true if both keys and values are equal. In normal comparison with type conversion in strict comparison without type conversion.
  • Same logic applies to the inequality (!= <>) and strict inequality (!==) checks.

Conditional Statements #1:

simple if else

$condition = true;

if ($condition) {
    echo “true”;
} else {
    echo “false”;
}
// prints true

nested if else

$firstCondition = true;
$secondCondition = true;
$thirdCondition = true;

if ($firstCondition) {
    echo "true";
    if ($secondCondition && $thirdCondition) {
        echo " and true";
    }
} else {
    echo "false";
}
// prints true and true

elseif

$firstCondition = true;
$secondCondition = false;

if ($firstCondition && $secondCondition) {
    echo "both true";
} elseif ($firstCondition || $secondCondition) {
    echo "one true";
} else {
    echo "none true";
}
// prints one true
  • Operators who can be used are: ==, ===, !=, <>, !==, >. <, >=, <=, &&, and, ||, or, xor and !.

one line if

$condition = true;

if ($condition) $result = “true”;
echo $result;
// prints true

one line if else

$condition = true;

$result = $condition ? “true” : “false”;
echo $result;
// prints true

Conditional Statements #2:

switch statement

$paymentStatus = "paid";

switch ($paymentStatus) {

     case "paid":
           echo "Payment is paid";
           break;

     case "declined":
     case "rejected":
            echo "Payment decliend";
            break;
 
     default:
            echo "Unkown payment status";
}

//prints Payment is paid

switch with break 2

$paymentStatuses = ["paid", "rejected"];

foreach ($paymentStatuses as $paymentStatus) {
  switch ($paymentStatus) {

     case "paid":
           echo "Payment is paid";
           break 2;

     case "declined":
     case "rejected":
            echo "Payment decliend";
            break 2;
 
     default:
            echo "Unkown payment status";
  }
}

//prints Payment is paid and then breaks out of both
  • The switch statement is similar to the if-else statement. The switch statement is slightly faster, but not notably so.
  • You can choose whichever is more readable to you, except in one case where the variable part is a function call.
  • If you remove the break statement, it will execute the next block until there’s another break or default, and it also does loose comparison.

While, Do While, For, Foreachloops:

while loop

$i = 0;

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

/* prints 
0123456789101112131415 */

while loop break

$x = true;
$i = 0;

while ($x) {
   while ($i > 10) {
      break 2;
   }
   echo $i++;
}

// prints 012345678910

while loop continue

$i = 0;

while ($i <= 15) {
   if ($i % 2 == 0) {
      $i++;
      continue;
   }
   echo $i++ . ",";
}

// prints 1,3,5,7,9,11,13,15,

alternative syntax

$i = 0;

while ($i <= 15):
   if ($i % 2 == 0) {
      $i++;
      continue;
   }
   echo $i++ . ",";
endwhile;

// prints 1,3,5,7,9,11,13,15,
  • The alternative syntax, the ‘break’ and ‘continue’ statements can be extended to subsequent loops, I just aimed to avoid unnecessary space.

do while loop

$i = 25;

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

/* prints 25 because
it’s executed only one time */

for loop

for ($i = 0; $i <= 15; $i++) {
     echo $i;
}

/* prints 0123456789101112131415 */

for loop with arrays

$text = ["h", "e", "l", "l", "o"];
$length = count($text);

for ($i = 0; $i < $length; $i++) {
     echo $text[$i];
}

// prints hello

foreach loops

$text = ["h", "e", "l", "l", "o"];

foreach ($text as $letter) {
      echo $letter;
}

// prints hello

A short introduction to functions:

simple function

function myAge() {
     echo "29 + 3";
}

myAge();
// prints 29 + 3

return function

function myAge() {
     return "29 + 3";
}

$x = myAge();
echo $x;
// prints 29 + 3

better not define functions conditionally (don’t do this)

echo myAge();

if (true) {
   function myAge() {
       return "29 + 3";
   }
}

/* Fatal error because not defined yet */

Type-hinting function returns

function myAge(): int {
     return "32";
}

echo myAge();

/* prints 32 because “32” gets converted into integer */

function parameter

function add(int $x, int $y) {
     return $x + $y;
}

echo add(5, “5”);

/* prints 10 because “5” gets converted into integer */

function parameter with defaults

function add(int $x, int $y = 5) {
     return $x + $y;
}

echo add(5);

// prints 10

simple function named arguments

function sum(int $x, int $y, int $z) {
    return $x + $y * $z;
}

echo sum(z: 5, y: 2, x: 10);

/* prints 20 and the order of the passed arguments is not relevant */
  • Functions in PHP are basically the same as in other languages. It takes an input, does something and returns a value.