PHP 8 Crash Course

What you need to know to become a PHP guru.

PHP remains a cornerstone of web development, powering countless websites and applications. This article provides a rapid introduction to PHP, covering fundamental concepts and progressing to more advanced techniques, to get you quickly up to speed.

PHP is compatible with various operating systems, including Windows, Linux, and macOS. Installation instructions and downloads can be found at php.net. While this tutorial doesn't focus on a specific operating system, the examples provided should be easily adaptable to any environment. You can verify your PHP installation and version by running php -v from your command line or terminal. Notice I am on version 8.2.1

php -v

PHP 8.2.1 (cli) (built: Jan  3 2023 23:31:58) (ZTS Visual C++ 2019 x64)
Copyright (c) The PHP Group
Zend Engine v4.2.1, Copyright (c) Zend Technologies

Now that PHP is installed lets go over the basics…and a bit beyond.

First, let's talk about comments. Comments are extremely useful and provide a wonderful way to document your code. There are two different kinds of comments in PHP - single-line comments and multi-line comments. Both are very useful.

// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line comment
It can span multiple lines
*/

#I also like to add comments before functions in a JSDocs format

//---------- begin function encodeHtml
/*
* @describe encodes html chars that would mess in  a browser
* @param str string string to encode
* @param convert_tabs boolean
* @return encodes html chars that would mess in  a browser
* @usage $html=encodeHtml($html);
*/
function encodeHtml($string='',$convert_tabs=0){
	//if string is empty just return it
	if(strlen($string)==0){return $string;}
	$string=str_replace('?','[[!Q!]]',$string);
	$string=str_replace(
		array('<','>','"'),
		array('<','>','"'),
		$string
	);
	$string=str_replace('?',' ',$string);
	$string=str_replace('[[!Q!]]','?',$string);
	return $string;
}

Next is code blocks. Unlike Python, PHP does not use indentation for code blocks. Instead PHP uses curly brackets { } to determine the boundaries of functions, loops, and if/else statements. Also, PHP ends each statement with a semicolon ;. Below are a couple examples of functions. Notice the curly brackets and semicolons.

/**
* @describe  wrapper for file_get_contents
* @param file string - name and path of file
* @return string
* @usage $data=getFileContents($afile);
*/
function getFileContents($file){
	if(!is_file($file)){
		return "getFileContents Error: No such file [$file]";
	}
	return file_get_contents($file);
}

/**
* @describe returns the extension of file
* @param file string - name and path of file
* @return string
* @usage $ext=getFileExtension($afile);
*/
function getFileExtension($file=''){
	$tmp=preg_split('/\./',$file);
	$ext=array_pop($tmp);
	return strtolower($ext);
}

Up next are variables. All variables in PHP start with a dollar sign $. PHP is a loosely typed language, meaning you don't need to declare the type of a variable explicitly. PHP automatically determines the type based on the value assigned to the variable. Below are examples of each data type. Notice that there are often multiple ways to define and manipulate variables in PHP.

$x = 10;  #int
$y = 9.45;  #float or double
$name = "Alice";  #string
$is_student = True;  #boolean  True or False

#arrays (called lists in Python)
$numbers = array();  #define an empty array
$numbers = [];  #also define an empty array
$numbers= [12,33,44,1];  #array definition with values
$numbers= array(12,33,44,1);  #also array definition with values
$numbers[]=63; #adds element to end
array_push($numbers,63); #also adds element to end
array_unshift($numbers,5);  #adds element to the beginning
$last = array_pop($numbers); #removes and returns the last item
$first = array_shift($numbers); #removes and returns the first item

# Constants for storing a fixed value
define("MAX_USERS", 100);
echo MAX_USERS;  // Output: 100

#Associative Arrays (called dictionaries in Python)
$d = array('name'=>'Bob','age'=>32);
$d = ['name'=>'Bob','age'=>32];
# NOTE: arrays can also contain Associative Arrays
$recs = [
    ["name" => "bob", "age" => 22],
    ["name" => "sam", "age" => 19]
];

PHP has some really great functions for manipulating text strings. Review the following code carefully as you will use these a ton.

<?php
//create a string
$text = "Hello, World!";

//upper case the whole string
strtoupper($text)	// HELLO, WORLD!
//lower case the whole string
strtolower($text)	// hello, world!
//uppercase the first letter only (notice I lowercase it first)
ucfirst(strtolower($text))	// Hello, world!
//uppercase the first letter of each word (notice I lowercase it first)
ucwords(strtolower($text))	// Hello, World! 

// Case Sensitive Searching
strpos($text, "World")	// position of the first occurrence
strrpos($text, "World")	// position of the last occurrence
substr_count($text, "l")	// Returns 3 (number of occurrences)
str_contains($text, "World")	// String Contains (boolean)
str_starts_with($text, "Hello") // String Starts With (boolean)
str_ends_with($text, "!")	//String Ends With (boolean)
// Case InSensitive Searching
stripos($text, "world")	// position of the first occurrence

// Whitespace handling
echo trim($text) . PHP_EOL;   // Removes whitespace from both ends
echo ltrim($text) . PHP_EOL;  // Removes whitespace from left
echo rtrim($text) . PHP_EOL;  // Removes whitespace from right

// Splitting and joining
$parts = explode(",", $text); // Splits into array
$parts = preg_split('/\,/',$text); //Splits into array using preg
$text = implode(",", $parts); // Joins array with separator:
$p = substr($text,0,3);	//Substring - returns first three characters of $text

// Replacement
str_replace("World", "PHP", $text)	//replace World with PHP in $text string

// Double-quoted string interpolation
$person = "Name: {$name}, Age: {$age}";   
// sprintf() method  
$person = sprintf("Name: %s, Age: %d", $name, $age);           

?>

In If, elseif, else statements

$x=4;
//check the value of $x
if($x > 10){
	echo "x is greater than 10".PHP_EOL;
}
elseif($x == 10){
    echo "x is 10".PHP_EOL;
}
else{
    echo "x is less than 10".PHP_EOL;
}

Loops allow you to iterate through arrays and associative arrays.


<?php
// Iterate an array (list in python)
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
    echo $fruit . PHP_EOL;
}

// Iterate an associative array (dictionary in python)
$person = ['name' => 'Alice', 'age' => 30, 'city' => 'New York'];
foreach ($person as $key => $value) {
    echo "{$key}: {$value}". PHP_EOL;
}

// Iterate an array of associative arrays in PHP (list of dictionaries in Python)
$people = [
    ["name" => "bob", "age" => 22],
    ["name" => "sam", "age" => 19]
];
foreach ($people as $person) {
    echo "Name: {$person['name']}, Age: {$person['age']}".PHP_EOL;
}

While loops are also useful when you need to repeat code as long as a specific condition is true. NOTE below that IF you do not increment $count in your while loop that it will never get out and you will have what is called an infinite loop. This is bad :

<?php
// example while loop
$count = 0;
while ($count < 5) {
    echo "Count is: {$count}".PHP_EOL;
    $count++;
}

As you have seen in earlier examples, Functions are defined with function

//example greet function
function greet($name){
    return "Hello, " . $name.PHP_EOL;
}
echo greet("Alice");

Files - To read and write to files, use the open() function. The second parameter specifies the mode: w for write, r for read, and a for append.

<?php
// Writing to a file - use w
$file = fopen("file.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);

// Reading from a file - use r
$file = fopen("file.txt", "r");
$content = fread($file, filesize("file.txt"));
echo $content;
fclose($file);

// Appending to an existing file - use a
$file = fopen("file.txt", "a");
fwrite($file, "Hello, World!");
fclose($file);

// Alternative simpler methods for basic operations
// Writing
file_put_contents('/var/www/example.txt', 'Another line of text' . PHP_EOL);  
// Reading
$content = file_get_contents('/var/www/example.txt');  // Reading

For error handling use the try/catch or try/catch/finally method

<?php
// Catches a division by zero error
try {
    $result = 10 / 0;  // Raises DivisionByZeroError
} catch (DivisionByZeroError $e) {
    echo "Cannot divide by zero!";
}

// Handle errors when file is not found
try {
    $file = fopen('/var/www/example.txt', 'r');
    // file operations
} catch (Exception $e) {
    echo "File not found";
} finally {
    if (isset($file)) {
        fclose($file);  // Ensures file is closed if it was opened
    }
}

Lastly, to include other code blocks or functions PHP has include, include_once, require, and require_once.

<?php
/* 
	include
	Will attempt to include the file and continue execution even if file is not found
	Generates a WARNING on failure
*/
include 'header.php';
echo "This will still run even if header.php is missing";

/* 
	include_once
	Same as include but checks if the file has already been included
	Will not include the same file twice
*/
include_once 'config.php';  // First inclusion
include_once 'config.php';  // Will be ignored as file was already included

/* 
	require
	Will attempt to include the file and STOP execution if file is not found
	Generates a FATAL ERROR on failure
*/
require 'database.php';  // Script will die here if database.php is missing
echo "This won't run if database.php is missing";

/*
	require_once
	Same as require but checks if the file has already been included
	Will not include the same file twice
*/
require_once 'functions.php';  // First inclusion
require_once 'functions.php';  // Will be ignored as file was already included

Congratulations on making it to the end of this article! If you're feeling a bit overwhelmed, I highly recommend re-reading it at least three more times before next Friday. Repetition will help immensely. You'll be surprised how much it aids you on your path to becoming a PHP guru.

 Sponsor: Finger Point Foods is a free website service that allows you to check the contents of foods in the grocery store. MUCH easier that checking every label on every product you are buying. Tons of features. Check it out. https://appstore.wasql.com/foods

Thanks again for reading. Please like and SHARE. đź™‚