Creating Variables
Example: $number = 10;
Printing Variables
Use echo
to display the value: echo $number;
outputs 10
.
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)
Shorthand Operations
Addition: num += 25;
(Equivalent to num = num + 25;
)
Other operations: num -= 25;
, num *= 25;
, num /= 25;
Using Built-in Functions
Absolute Value: abs(-100);
returns 100
.
Power: pow(2, 4);
returns 16
.
Square Root: sqrt(144);
returns 12
.
Maximum and Minimum:
max(2, 10);
returns 10
.
min(2, 10);
returns 2
.
Rounding Functions:
round(2.5);
returns 3
.
ceil(3.3);
returns 4
.
floor(3.9);
returns 3
.
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 $_POST
to retrieve submitted data:
echo grades[$_POST['student']];
Key-Value Pairs
Store data in pairs, e.g., student names and grades.
Example:
$grades = array("Jim" => "A+", "Pam" => "B-", "Oscar" => "C+");
Using Keys to Access Values
Example: echo $grades["Jim"];
outputs A+
.
Updating Values
Example: $grades["Jim"] = "F";
changes Jim's grade.
Purpose of Functions
Group related code for specific tasks.
Example of a simple function:
function sayHi() {
echo "Hi!";
}
Defining a Function
Use the function
keyword.
Calling a Function
Simply use the function name followed by parentheses.
Purpose of Constructors
Automatically initialize object properties when an object is created.
Defining a Constructor
Use the __construct
method:
function __construct($title, $author, $pages) {
$this->title = $title;
$this->author = $author;
$this->pages = $pages;
}
Example of Object Creation
Create a new book object:
$book1 = new Book("Harry Potter", "JK Rowling", 400);
Simplifies Object Creation
Reduces lines of code and potential errors.
Example of Accessing Object Properties
echo $book1->title;
outputs Harry Potter
.
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.