Concepts for PHP
PHP is a popular server-side scripting language widely used for web development. Originally created by Rasmus Lerdorf in 1994, PHP stands for "Hypertext Preprocessor." PHP is designed to be embedded within HTML code, allowing developers to create dynamic web pages and interact with databases easily. Key features of PHP include its simplicity, flexibility, and extensive support for web development tasks such as form processing, file handling, and session management. PHP also offers compatibility with various databases like MySQL, PostgreSQL, and SQLite, making it suitable for building dynamic, database-driven websites and web applications. Additionally, PHP has a large community of developers and a vast ecosystem of frameworks and libraries, further enhancing its versatility and usability for web development projects.
Print Text
echo "Hello World!";
Comments
// one line comment /* multi line comment */
Variables
$carCount = 2; $name = "Joe"; $isPurple = true;
Data Types
$carCount = 2; $age = 15; $seaLevel = -10000; $usBudget = 11000000000; $lightSpeed = 11799312874; $myGPA = 3.45; $piValue = 3.14159265; $lastLetter = 'Z'; $isMale = true; $myName = "Joe";
Math Op
$carCount = 6; $truckCount = 3; $total = $carCount + $truckCount; echo $total. "\n"; $subtract = $carCount - $truckCount; echo $subtract. "\n"; $multiple = $carCount * $truckCount; echo $multiple. "\n"; $divisible = $carCount / $truckCount; echo $divisible, "\n"; // performs division and gets remainder which is 0 $modulo = $carCount % $truckCount; echo $modulo. "\n";
Math Functions
$power = pow(3, 6); echo $power. "\n"; $root = sqrt(16); echo $root. "\n"; $floorVal = floor(3.14); echo $floorVal. "\n"; $ceilVal = ceil(4.3); echo $ceilVal. "\n"; $roundVal = round(3.4); echo $roundVal. "\n"; // random number from 0 to 100 $random_number = mt_rand(0, 100); echo $random_number. "\n";
If/Else
$carCount = 6; if ($carCount > 3) { echo "More than three cars"; } elseif ($carCount == 3) { echo "Equal to three cars"; } else { echo "Less than three cars"; }Ternary
$carCount = 3; $result = $carCount > 2 ? "Yes" : "No"; echo $result;
Switch
$carCount = 3; switch ($carCount) { case 1: echo "One car"; break; case 2: echo "Two cars"; break; case 3: echo "Three cars"; break; default: echo "More than three"; }Functions
function handleCars($cars, $wheels) { $total = $cars * $wheels; return $total; } $result = handleCars(3, 4); echo $result;Interpolation
$name = "Joe"; $car = "Mazda"; $result = "{$name} drives a {$car}"; echo $result;Type Casting
function squareA($length) { $result = pow($length, 2); return strval($result); } $squareL = "4"; $convertedVal = intval($squareL); $area = squareA($convertedVal); echo $area;Date and Time
// get current time in seoconds since Jan 1 1970 $secondTime = floor(microtime(true)); echo $secondTime . "\n"; // get current year $year = date("Y"); echo $year . "\n"; // full date in month day year format $fullDate = date("m/d/Y"); echo $fullDate . "\n"; // get current time in EST date_default_timezone_set("America/New_York"); $time = date("h:i:sa"); echo $time . "\n";Classes
class Cars { protected $carList = array(); public function addCar($car) { array_push($this->carList, $car); } public function removeFirst() { array_shift($this->carList); } public function getFirstVal() { if (count($this->carList) > 0) { return $this->carList[0]; } return ""; } } $newList = new Cars(); $newList->addCar("Honda"); $newList->addCar("Mazda"); $newList->addCar("Toyota"); $newList->removeFirst(); $firstCar = $newList->getFirstVal();Inheritance
class User { protected $username; protected $password; public function __construct( $username, $password ) { $this->username = $username; $this->password = $password; } } class Admin extends User { protected $id; public function __construct( $username, $password, $id ) { $this->username = $username; $this->password = $password; $this->id = $id; } public function getUsername() { return $this->username ."\n"; } public function getAdminID() { return $this->id; } } $newAdmin = new Admin( "alpha0", "pw1", "1FE" ); echo $newAdmin->getUsername(); echo $newAdmin->getAdminID();Method Overload
// No Native Support or Implementation
Abstract Class
abstract class Animation { abstract public function walk(); abstract public function run(); abstract public function idle(); } class Human extends Animation { public function walk() { echo "Human walks". "\n"; } public function run() { echo "Human runs". "\n"; } public function idle() { echo "Human idles". "\n"; } } class Zombie extends Animation { public function walk() { echo "Zombie walks". "\n"; } public function run() { echo "Zombie runs". "\n"; } public function idle() { echo "Zombie idles". "\n"; } } $player = new human(); $player->walk(); $boss1 = new Zombie(); $boss1->run();Static Class
class Helper { public static function circleA($radius) { $power = pow($radius, 2); return (3.14 * $power); } public static function squareA($length) { return pow($length, 2); } }; $circle = Helper::circleA(3); echo $circle . "\n"; $square = Helper::squareA(4); echo $square . "\n";Arrays/Lists
$names = array("Joe", "Alex", "Bob"); $names[1] = "Tom"; $name = $names[1]; $numItems = sizeof($names); echo "$name \n"; echo $numItems;Array Methods
$cars = array("Honda", "Mazda", "Toyota"); // slices from index 1 which starts new array $newList = array_slice($cars, 1); echo $newList[0]."\n"; echo $cars[0]."\n"; // inserts value to end of array array_push($cars, "Ford"); echo $cars[count($cars) - 1]."\n"; // removes last element of array array_pop($cars); echo $cars[count($cars) - 1]."\n"; // inserts value to beginning of array array_unshift($cars, "Kia"); echo $cars[0]."\n"; // removes first element of array array_shift($cars); echo $cars[0]."\n\n"; // sorts values in alphabetical order sort($cars); for ($i = 0; $i < count($cars); $i++) { echo $cars[$i]." "; }Concatenation
$carsListKr = ['Kia', 'Hyundai', 'Daewoo']; $carsListJp = ['Honda', 'Mazda', 'Toyota']; $combined = array_merge($carsListKr, $carsListJp); echo $combined[1] . "\n"; echo $combined[4];
Sort Method
$ages = array(5, 3, 1, 6, 7, 4, 19); sort($ages); for ($i = 0; $i < count($ages); $i++) { echo "{$ages[$i]}\n"; }Objects
class User { public $first; public $last; public $age; public $retired; public $carBrands; function set_user( $first, $last, $age, $retired, $carBrands) { $this->first = $first; $this->last = $last; $this->age = $age; $this->retired = $retired; $this->carBrands = $carBrands; } function full_name() { return $this->first . " " . $this->last; } } $brands = array("Mazda", "Toyota"); $user = new User(); $user->set_user( "Joe", "Doe", 23, false, $brands ); echo $user->first . "\n"; echo $user->carBrands[1] . "\n"; echo $user->full_name();Maps (Key/Value)
$ordinals = [ 'Joe' => 'Toyota', 'Bob' => 'Mazda', 'Tom' => 'Ford', ]; echo $ordinals['Tom'] . "\n"; unset($ordinals['Tom']); echo count($ordinals);Sets
// No Native Support or Implementation // Use PECL and DS library
Stack
$cars = array(); array_push($cars, "Mazda"); array_push($cars, "Toyota"); array_push($cars, "Honda"); echo $cars[count($cars) - 1] . "\n"; array_pop($cars); echo $cars[count($cars) - 1];
Queues
$cars = array(); array_push($cars, "Mazda"); array_push($cars, "Toyota"); array_push($cars, "Honda"); echo $cars[0] . "\n"; array_shift($cars); echo $cars[0];
Linked List
class Node { public $value; public $next; public function set_value($value) { $this->value = $value; } } class LinkedList { public $head = null; public function add($value) { $newNode = new Node(); $newNode->set_value($value); if ($this->head === null) { $this->head = $newNode; } else { $current = $this->head; while ($current->next) { $current = $current->next; } $current->next = $newNode; } } public function returnHead() { return $this->head->value; } public function traverse() { $current = $this->head; while($current) { echo $current->value ."\n"; $current = $current->next; } } } $carList = new LinkedList(); $carList->add("Mazda"); $carList->add("Toyota"); $carList->add("Honda"); echo $carList->returnHead() ."\n"; $carList->traverse();Graphs
class Graph { public $graphMap = array(); public function addNode($val) { $this->graphMap[$val] = array(); } public function addVertices($node1, $node2) { if (array_key_exists( $node1, $this->graphMap) == false) { $this->graphMap[$node1] = array(); } if (array_key_exists( $node2, $this->graphMap) == false) { $this->graphMap[$node2] = array(); } array_push($this->graphMap[$node1], $node2); array_push($this->graphMap[$node2], $node1); } public function breadthTraverse($start) { $queue = array($start); $visited = array(); $visited[$start] = true; while(count($queue) > 0) { $val = array_shift($queue); echo $val. "\n"; $tempArr = $this->graphMap[$val]; for ($i = 0; $i < count($tempArr); $i++) { if (array_key_exists( $tempArr[$i], $visited) == false) { array_push($queue, $tempArr[$i]); $visited[$tempArr[$i]] = true; } } } } public function depthTraverse($start) { $stack = array($start); $visited = array(); $visited[$start] = true; while(count($stack) > 0) { $val = array_pop($stack); echo $val, "\n"; $tempArr = $this->graphMap[$val]; for ($i = 0; $i < count($tempArr); $i++) { if (array_key_exists( $tempArr[$i], $visited) == false) { array_push($stack, $tempArr[$i]); $visited[$tempArr[$i]] = true; } } } } } $newGraph = new Graph(); $newGraph->addNode("a"); $newGraph->addVertices("a", "b"); $newGraph->addVertices("a", "c"); $newGraph->addVertices("b", "d"); $newGraph->addVertices("b", "e"); $newGraph->addVertices("d", "f"); $newGraph->addVertices("d", "g"); $newGraph->addVertices("d", "h"); $newGraph->addVertices("e", "i"); $newGraph->addVertices("e", "j"); $newGraph->breadthTraverse("a"); $newGraph->depthTraverse("a");For Loops
$names = array("Joe", "Alex", "Bob"); for ($i = 0; $i < sizeof($names); $i++) { echo $names[0]; echo "\n"; }While Loops
$carList = array('Mazda', 'Toyota', 'Honda'); while (count($carList) > 0) { echo $carList[0]. "\n"; array_shift($carList); } echo count($carList). "\n";Loop Breaks
$cars = array('Toyota', 'Honda', 'Mazda'); for ($i = 0; $i < count($cars); $i++) { if ($cars[$i] == 'Honda') { echo "Found at index {$i}\n"; break; } echo "Visted index {$i}\n"; }Recursion
function getSum($arr) { if (sizeof($arr) == 0) return 0; $val = $arr[0]; array_shift($arr); return $val + getSum($arr); } $testArr = array(1, 2, 4, 5); $sum = getSum($testArr); echo $sum;Regex Words
$pattern = "/\w+/"; $phrase = "I am legend"; preg_match($pattern, $phrase, $matches); echo $matches[0];
Regex Numbers
$pattern = "/\d+/"; $phrase = "I am 23"; preg_match($pattern, $phrase, $matches); echo $matches[0];
Regex Test
$pattern = "/Lee/"; $phrase = "Bob Lee"; $result = preg_match($pattern, $phrase); echo $result;
Regex Characters
$pattern = "/#+\w+/"; $phrase = "##I am Legend##"; preg_match($pattern, $phrase, $matches); echo $matches[0];