PHP Programming Language Tutorial - Full Course
PHP Basics: Variables and Math Operations
Storing Numbers in Variables
Creating Variables
Example:
$number = 10;
Printing Variables
Use
echoto display the value:echo $number;outputs10.
Performing Operations with Variables
Addition of Variables
Example:
$anotherNumber = 5; echo $number + $anotherNumber; // Outputs 15
Incrementing and Decrementing
Increment:
$number++;(Increases value by 1)Decrement:
$number--;(Decreases value by 1)
Arithmetic Operations
Shorthand Operations
Addition:
num += 25;(Equivalent tonum = num + 25;)Other operations:
num -= 25;,num *= 25;,num /= 25;
Advanced Math Functions in PHP
Using Built-in Functions
Absolute Value:
abs(-100);returns100.Power:
pow(2, 4);returns16.Square Root:
sqrt(144);returns12.Maximum and Minimum:
max(2, 10);returns10.min(2, 10);returns2.
Rounding Functions:
round(2.5);returns3.ceil(3.3);returns4.floor(3.9);returns3.
User Input in PHP
Setting Up Forms
Forms allow user interaction and data submission.
Basic HTML form structure:
<form action="site.php" method="POST"> <input type="text" name="student"> <input type="submit" value="Submit"> </form>
Accessing User Input
Use
$_POSTto retrieve submitted data:echo grades[$_POST['student']];
Associative Arrays in PHP
Introduction to Associative Arrays
Key-Value Pairs
Store data in pairs, e.g., student names and grades.
Example:
$grades = array("Jim" => "A+", "Pam" => "B-", "Oscar" => "C+");
Accessing Associative Array Elements
Using Keys to Access Values
Example:
echo $grades["Jim"];outputsA+.
Modifying Associative Arrays
Updating Values
Example:
$grades["Jim"] = "F";changes Jim's grade.
Functions in PHP
Introduction to Functions
Purpose of Functions
Group related code for specific tasks.
Example of a simple function:
function sayHi() { echo "Hi!"; }
Creating and Using Functions
Defining a Function
Use the
functionkeyword.
Calling a Function
Simply use the function name followed by parentheses.
Constructors in PHP
Understanding Constructors
Purpose of Constructors
Automatically initialize object properties when an object is created.
Defining a Constructor
Use the
__constructmethod:function __construct($title, $author, $pages) { $this->title = $title; $this->author = $author; $this->pages = $pages; }
Creating Objects with Constructors
Example of Object Creation
Create a new book object:
$book1 = new Book("Harry Potter", "JK Rowling", 400);
Benefits of Using Constructors
Simplifies Object Creation
Reduces lines of code and potential errors.
Example of Accessing Object Properties
echo $book1->title;outputsHarry Potter.
Summary
Understanding variables, math operations, user input, associative arrays, functions, and constructors is crucial for effective PHP programming.
These concepts form the foundation for building dynamic and interactive web applications.