PHP

PHP is a language that is embedded within an HTML file. It doesn't have to be within an HTML document, though.

Syntax

PHP code must be enclosed within special tags: <?php and ?>

<?php
  $hello = "Hello"
  $world = "world"
  // Say hello
  echo "{$hello}, " . "{$world}!";
?>

Variables

Variables are prefaced by a $.

<?php
$x = 4;
$y = "Yeah";
$z = True;

Constants

Constants are usually defined as all uppercase. They are called without the $ for some reason.

<?php
define('CONSTANT', 1);
echo CONSTANT; // 1

Function

Functions are defined similar to Javascript. They are part of the global scope.

<?php
function example($arg1, $arg2 = "Yeah") {
  echo "Yay";
  return 1;
}

example("1");
example("1", "2");

Anonymous functions

Anonymous functions, including arrow functions, are defined as variables and not as part of the global scope.

<?php
$add = function($num1, $num2) {
  return $num1 + $num2;
}

$add(5, 5);

Arrow functions automatically use any included variables. The following functions are equivalent:

<?php
$startNum = 100;

$subStartNum = function ($num1) use ($startNum) {
    return $num1 - $startNum;
}

// Note there is no `use`
$subStartNumArrow = fn($num1) => $num1 - $startNum;

$subStartNum(5); // 95
$subStartNumArrow(5); // 95

Scope

Functions create a scope where variables defined within are only accessible within, but also that variables defined outside of the scope are not readily accessible. To access a globally scoped variable, the variable must be introduced with a global call.

<?php
$outside = "test";

function example() {
  // echo $outside;  This will error out
  global $outside;
  echo $outside;

  $inside = "We are no longer " . $outside;

  return 1;
}

// echo $inside;  This will error out

Super Globals[3]

Super globals are variables that are available at all levels and scopes. These include system information, request information, cookies, etc.

Name Has info about
$GLOBALS Variables in global scope.
$_GET Variables passed through a URL or a form.
$_POST Variables passed through a form.
$_COOKIE Variables passed through a cookie.
$_SESSION Variables passed through a session.
$_SERVER The server environment.
$_ENV The environment variables.
$_FILES Files uploaded to the script.
$_REQUEST Variables passed through the form or URL.

Data Types

String Methods

Strings can be concatenated using ..

<?php
$str = "Hello, " . "World!";
$str .= " Good afternoon, good evening, and goodnight.";

String formatting can be performed as it is in shell scripts, by using double quotes.

<?php
$name = "John";
$greeting = "Hello, $name";
$ending = "Goodbye, {$name}";
$not_correct = 'Hello, $name'; // prints 'Hello, $name'

htmlspecialchars(str) will escape all HTML characters in a string, making you safer from script injections.

Alternatively, if the input string is a cookie, GET value, etc., you can use filter_input[4], which has special rules and helper variables.

Arrays

Basic arrays are just associative arrays with zero-indexing.

<?php
$numbers = [1,2,3,4];
// or
$numbers = array(1,2,3,4);

$first_item = $numbers[0];

Associative arrays are like Javascript objects or Python dictionaries.

<?php
$people = {
  "john" => 55,
  "jane" => 19,
  "bob" => 11,
  "jill" => 92
};

$john_age = $people["john"];

Methods

Method Args Effect
sizeof(arr) Get size of array.
array_push(arr, val1[, val2...]) Add elements to end of array
array_pop(arr) Pop element off end of array
array_shift(arr) Pop element off beginning of array
array_unset(arr[n]) n: Index of element Delete element from array while maintaining order
array_chunk(arr, n) n: Max number of elements per "chunk" Break up array into an array of regular sized subarrays
array_merge(arr1, arr2) Concatenate arr2 to the end of arr1 and return concatenated array
[...arr1, ...arr2] Same as above
array_combine(arr1, arr2) Create associative array using arr1 as keys and arr2 as values. Like Python's zip.
array_keys(assArr1) Make array of keys from an associative array
array_flip(assArr1) Flip keys and values in an associative array
range(start, end) Create array of values from start to end, inclusive
array_map(fn(n) => any, arr) For each item in array, run callback and add return to resulting array
array_filter(arr, fn(n) => bool) For item, if result of callback is true, add to return array.
array_reduce(arr, fn(lastResult, n) => result) For item, run callback and use previous result of array as lastResult of next iteration, ending with the final result as return.

Conditionals

Conditionals are written the same way as Javascript, in terms of if blocks, except elseif is together instead of separated. Ternary statements and switch cases are the same as well.

Like Javascript, PHP has double- and triple-equals for testing equality; double is for testing equal in value, triple is for testing identical in value and type.

Conditional HTML

PHP can render HTML conditionally without resorting to running echo everywhere.

<?php if ($loggedIn) { ?>
  <h1>You are logged in!</h1>
  <p>Any valid HTML will be conditionally rendered</p>
<?php } else if ($var === 1) { ?>
  <p>Something else</p>
<?php } else { ?>
  <p>Last thing</p>
<?php } ?>

<p> Or you can do this: </p>

<?php if ($loggedIn): ?>
  <h1>You are logged in!</h1>
  <p>Any valid HTML will be conditionally rendered</p>
<?php else if ($var === 1): ?>
  <p>Something else</p>
<?php else: ?>
  <p>Last thing</p>
<?php endif ?>

Loops

For loops, while loops, and do while loops are the same as Javascript.

The foreach loop is unique to PHP in that it is similar to Javascript's .forEach method on iterables, but is a statement that takes in an array or associative array as an expression:

<?php
$posts = ["title1", "title2", "title3"];

foreach ($posts as $post) {
  echo $post;
}

$posts = {
  "title1" => "Content1",
  "title2" => "Content2",
  "title3" => "Content3"
};

foreach ($posts as $key => $value) {
  echo $key . " - " . $value;
}

Classes

<?php
class User {
    public $name;
    public $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }

    public function login() {
        echo $this->name . ' has logged in!';
    }
}

Class methods can be public, (the default), protected which makes access possible by that class and those that inherit it, or private which makes access possible only by that class.

Classes can use inheritance through the extends keyword.

<?php
class Person {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }
}

class Brother {
    public $is_annoying;

    // Takes all args from parent class
    public function __construct($name, $is_annoying) {
        // Instantiates all attributes from parent
        parent::__construct($name);
        $this->is_annoying = $is_annoying;
    }
}

Common Functions

echo (multiple values), print (single value), print_r (for arrays).

When debugging, use var_dump for more info or var_export for type representation.

A shorthand in PHP for echoing out a single line to the page is <?= 'Hello there' ?> instead of <?php echo 'Hello there' ; ?>.

You can start a local server in a given folder by running php -S localhost:8000 (or whatever port).

Requests

To set a cookie, use setcookie(name, value, exp).

Importing/including files

You can use include, which fails gracefully, and require, which errors if the file is not found.

heading.php

<h1>Heading</h1>

index.php

<?php include 'heading.php'; ?>
<p> Hello there</p>

References

  1. https://www.learn-php.org/en/Hello%2C_World%21
  2. https://piped.kavin.rocks/watch?v=BUCiSSyIGGU
  3. https://www.php.net/manual/en/language.variables.superglobals.php
  4. https://www.php.net/manual/en/function.filter-input.php
  5. https://stackoverflow.com/questions/3812526/conditional-statements-in-php-code-between-html-code
  6. https://www.tutorialspoint.com/php/php_sending_emails.htm
  7. PHP: The Right Way
  8. PHP with SQLite3 using PDO
Incoming Links

Last modified: 202410290345