0% found this document useful (0 votes)
2 views

Chapter 2 - PHP Fundamentals

Chapter 2 of 'Internet Programming II' introduces PHP, a server-side scripting language essential for web development, highlighting its features such as dynamic content generation, database connectivity, and security. It covers PHP syntax, file structure, variables, data types, operators, control structures, and functions, providing examples and practice exercises for better understanding. The chapter emphasizes PHP's versatility, performance improvements in version 8.4, and its active community support.

Uploaded by

redietgeremew18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 2 - PHP Fundamentals

Chapter 2 of 'Internet Programming II' introduces PHP, a server-side scripting language essential for web development, highlighting its features such as dynamic content generation, database connectivity, and security. It covers PHP syntax, file structure, variables, data types, operators, control structures, and functions, providing examples and practice exercises for better understanding. The chapter emphasizes PHP's versatility, performance improvements in version 8.4, and its active community support.

Uploaded by

redietgeremew18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Internet Programming II

Chapter 2
PHP SYNTAX and BASIC CONCEPTS
Introduction
PHP, which stands for "Hypertext Preprocessor", is a widely-used server-side scripting language designed
primarily for web development. It was initially created by Rasmus Lerdorf in 1993 and has since evolved
into a powerful tool that powers millions of websites and web applications worldwide. Unlike client-side
languages like JavaScript, which execute code on the user's browser, PHP runs on the server, processes
the script, and sends the resulting HTML output to the client. This ensures better security, as the actual
PHP code remains hidden from users.

PHP is open-source and continuously improved by a large community of developers. The latest version,
PHP 8.4, released in November 2024, introduces significant performance enhancements, improved error
handling, and new features for modern web development. Due to its simplicity, flexibility, and efficiency,
PHP remains one of the most popular programming languages for building dynamic and interactive
websites, content management systems (CMS), and web applications.

Characteristics of PHP
PHP offers numerous features that make it an essential tool for web developers:

 Versatile File Structure: PHP files can contain a mix of HTML, CSS, JavaScript, and PHP code,
making it easy to integrate with front-end technologies.
 Dynamic Content Generation: PHP allows websites to generate dynamic content, such as
displaying personalized information, handling user input, and updating page content in real time.
 Database Connectivity: PHP supports various databases (MySQL, PostgreSQL, SQLite, etc.),
making it easy to build database-driven web applications.
 User Authentication and Access Control: PHP enables secure user authentication and role-based
access control, ensuring that sensitive data is protected.
 File Handling Capabilities: PHP provides built-in functions for reading, writing, modifying, and
deleting files on the server.

1 of 19
Internet Programming II

 Cross-Platform Compatibility: PHP runs on multiple operating systems, including Windows, Linux,
macOS, and Unix, and is compatible with almost all web servers, such as Apache and Nginx.
 Dynamic Typing and Flexibility: PHP is dynamically typed, meaning variables do not require explicit
type declarations. This makes it easy to work with different data types without strict constraints.
 Security Features: PHP includes built-in features for encryption, data validation, session
management, and protection against SQL injection and XSS attacks.
 Fast and Efficient: PHP executes code quickly and efficiently, with modern versions significantly
improving performance.
 Active Community and Documentation: Being open-source, PHP has extensive documentation
and a large developer community, making it easy to find support, tutorials, and libraries for
various applications.

Understanding PHP File Structure and Syntax


PHP is a server-side scripting language that seamlessly integrates with HTML. All PHP files should have the
.php extension. PHP code is enclosed within <?php ... ?> tags.

Example of a basic PHP file:

<?php
echo "Hello, PHP World!";
?>
PHP can also be mixed with HTML:

<!DOCTYPE html>
<html>
<body>
<h1>Welcome to PHP</h1>
<?php
echo "Today is " . date("l") . "!";
?>
</body>
</html>

2 of 19
Internet Programming II

Writing and Executing a Simple PHP Script


To run a PHP script, you need a local server like XAMPP, WAMP, or LAMP. Save your file as index.php
and place it inside the htdocs (for XAMPP) or www (for WAMP) folder. Open your browser and enter
http://localhost/index.php to see your PHP script in action.

Comments in PHP
Comments help explain the code and are ignored during execution. PHP supports single-line and multi-
line comments.

Single-line comments:

// This is a single-line comment


# This is another way to write a single-line comment

Multi-line comments:

/*
This is a multi-line comment.
It spans multiple lines.
Useful for explaining complex code.
*/

Displaying Output Using echo and print

Both echo and print are used to output data to the browser.

Example using echo:


echo "Hello, World!";
echo "<br>Welcome to PHP!";

Example using print:


print "Hello, World!";
print "<br>Learning PHP is important.";

The key difference between echo and print is that echo can output multiple values, while print
returns a value (1), making it slightly slower.

Practice Exercises
Modify the example code to display your name dynamically. Use comments to explain each line of your
code. Try using both echo and print in the same script.

By practicing these exercises, you will develop a strong understanding of PHP syntax and basic concepts.

3 of 19
Internet Programming II

How PHP Works


PHP is a server-side scripting language, meaning that its code is executed on the server rather than in the
user's browser. This makes PHP secure, efficient, and capable of generating dynamic content.

The typical execution process of a PHP script follows these steps:

1. User Request: A user requests a PHP page by entering a URL in their browser (e.g.,
http://example.com/index.php).
2. Server Processing: The web server (e.g., Apache, Nginx, IIS) receives the request and forwards it
to the PHP interpreter for execution.
3. PHP Script Execution: The PHP engine processes the script, which may include:
 Retrieving data from a database (e.g., MySQL, PostgreSQL).
 Handling user input (e.g., form submissions, session management).
 Performing calculations or logical operations.
 Generating dynamic HTML content.
4. HTML Output Generation: PHP generates plain HTML output, which is sent back to the client’s
browser for rendering.
5. Client-Side Display: The browser displays the final web page, but the actual PHP code remains
hidden, ensuring security and confidentiality.

Variables and Data Types


Understanding variables and data types is fundamental to programming in PHP. This section covers how
to declare and use variables, the different data types available in PHP, and how PHP handles type juggling
and type casting.

Declaring and Using Variables


PHP variables store data that can change during script execution. A variable is declared using the $ symbol,
followed by the variable name. Unlike some other programming languages, PHP does not require explicit
data type declarations.

4 of 19
Internet Programming II

Example:

$name = "John";
$age = 25;
$price = 19.99;
$isAvailable = true;
Variable names in PHP must start with a letter or an underscore and cannot contain spaces. They are case-
sensitive, meaning $name and $Name are considered different variables.

PHP Data Types


PHP supports several data types that help manage different kinds of information.
1. String: A sequence of characters enclosed in single or double quotes.
$text = "Hello, World!";
2. Integer: A whole number without decimals.
$count = 100;
3. Float: A number with a decimal point.
$price = 10.99;
4. Boolean: Represents either true or false.
$is_admin = true;
5. Array: A collection of values stored under a single variable.
$colors = ["red", "green", "blue"];
6. Object: Represents an instance of a class.
class Car {
public $brand;
}
$myCar = new Car();
$myCar->brand = "Toyota";
7. NULL: Represents a variable with no value.
$var = NULL;
8. Resource: A special type that holds references to external resources such as database
connections.
Type Juggling and Type Casting
PHP automatically converts variable types based on usage, a process known as type juggling. For example:

$sum = "5" + 10; // PHP automatically converts "5" to an integer


To explicitly convert a variable to a specific type, type casting is used:

$var = "123";
$int_var = (int)$var; // Converts string to integer

 intval(), floatval(), and boolval() functions can also be used for type conversion.

5 of 19
Internet Programming II

PHP Constants
 Constants store fixed values that cannot be changed during script execution.
 Declared using:

define("SITE_NAME", "MyWebsite");

 Constants are automatically global and accessible anywhere in the script.


 Unlike variables, they do not use the $ symbol and cannot be redefined.
 Useful for storing configurations, database credentials, and fixed values.
Example:

define("PI", 3.1416);
echo PI; // Output: 3.1416

Practice Exercises
1. Declare variables of different data types and print their values.
2. Experiment with type juggling by performing operations between different data types.
3. Use type casting to convert a float to an integer and observe the results.

Operators in PHP
Operators in PHP are used to perform operations on variables and values. This section covers different
types of operators, including arithmetic, comparison, logical, assignment, and string operators.con

Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values.

Operator Description Example Result

+ Addition $a + $b Sum of $a and $b

- Subtraction $a - $b Difference of $a and $b

* Multiplication $a * $b Product of $a and $b

/ Division $a / $b Quotient of $a and $b

% Modulus $a % $b Remainder of $a divided by $b

** Exponentiation $a ** $b $a raised to the power of $b

Example:
$x = 10;
$y = 3;
echo $x + $y; // Output: 13

6 of 19
Internet Programming II

Comparison Operators
Comparison operators compare two values and return a boolean (true or false).

Operator Description Example

== Equal to $a == $b

=== Identical (equal and same type) $a === $b

!= Not equal $a != $b

<> Not equal $a <> $b

!== Not identical $a !== $b

> Greater than $a > $b

< Less than $a < $b

>= Greater than or equal to $a >= $b

<= Less than or equal to $a <= $b

Example:

$a = 5;
$b = 10;
var_dump($a < $b); // Output: true

Logical Operators
Logical operators are used to combine multiple conditions.

Operator Description Example

&& AND $a && $b

|| OR $a || $b

! NOT !$a

Example:

$a = true;
$b = false;
var_dump($a && $b); // Output: false

7 of 19
Internet Programming II

Assignment Operators
Assignment operators are used to assign values to variables.

Operator Example Equivalent to

= $a = $b $a = $b

+= $a += $b $a = $a + $b

-= $a -= $b $a = $a - $b

*= $a *= $b $a = $a * $b

/= $a /= $b $a = $a / $b

%= $a %= $b $a = $a % $b

Example:

$x = 5;
$x += 3; // Equivalent to $x = $x + 3

String Operators
String operators are used to manipulate text values.

Operator Description Example

. Concatenation $a . $b

.= Append $a .= $b

Example:

$greeting = "Hello ";


$name = "John";
echo $greeting . $name; // Output: Hello John

Practice Exercises
1. Perform arithmetic operations on two variables and print the results.
2. Use comparison operators to compare values and display the output.
3. Write a script using logical operators to evaluate multiple conditions.
4. Concatenate two strings and display the output.

8 of 19
Internet Programming II

Control Structures (Conditionals and Loops)


Control structures in PHP are essential for executing specific blocks of code based on conditions or for
repeating actions multiple times. This section covers conditional statements and loop structures, which
are fundamental for efficient programming.

Conditional Statements
Conditional statements allow execution of specific code blocks based on given conditions. PHP provides
several ways to handle conditions: if, if...else, if...elseif...else, and switch.

1. if Statement

The if statement executes a block of code only if a specified condition evaluates to true.

$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}

2. if...else Statement

The if...else statement runs one block of code if the condition is true, and another if it is false.

$marks = 50;
if ($marks >= 50) {
echo "You passed the exam.";
} else {
echo "You failed the exam.";
}

3. if...elseif...else Statement

This statement allows multiple conditions to be checked in sequence.

$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";

9 of 19
Internet Programming II

} else {
echo "Grade: F";
}

4. switch Statement
The switch statement is used to compare a variable against multiple values.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the work week.";
break;
case "Friday":
echo "Weekend is coming!";
break;
default:
echo "Another regular day.";
}

Loop Structures
Loops allow execution of a block of code multiple times until a condition is met. PHP provides several
looping structures: for, while, do...while, and foreach.

1. for Loop

The for loop is used when the number of iterations is known beforehand.

for ($i = 1; $i <= 5; $i++) {


echo "Iteration: $i <br>";
}

2. while Loop

The while loop executes a block of code as long as the specified condition is true.

$count = 1;
while ($count <= 5) {
echo "Count: $count <br>";
$count++;
}

10 of 19
Internet Programming II

3. do...while Loop
This loop executes the block at least once before checking the condition.

$num = 1;
do {
echo "Number: $num <br>";
$num++;
} while ($num <= 5);

4. foreach Loop (for Arrays)

The foreach loop is specifically used for iterating over arrays.

$colors = ["Red", "Green", "Blue"];


foreach ($colors as $color) {
echo "Color: $color <br>";
}

Practice Exercises
1. Write a script using if...elseif...else to assign grades based on marks.
2. Use a switch statement to display messages for different days of the week.
3. Implement a for loop to print numbers from 1 to 10.
4. Create a while loop to print even numbers between 1 and 20.
5. Iterate through an associative array using a foreach loop and display key-value pairs.

2.8. Functions and Scope


Functions are an essential part of PHP programming, allowing developers to create reusable blocks of
code. By using functions, code can be better structured, more readable, and easier to maintain. This
section explores function creation, parameters, return values, variable scope, and passing arguments by
reference.

Creating and Using Functions


A function is a block of code that performs a specific task and can be called multiple times within a
program. Functions in PHP are defined using the function keyword.

Defining a Function

function greet() {
echo "Hello, welcome to PHP!";
}
In this example, calling greet(); will output "Hello, welcome to PHP!".
11 of 19
Internet Programming II

Calling a Function
Once defined, a function is executed when it is called:
greet();

Advantages of Using Functions


 Code reusability: Functions prevent repetition by allowing reuse of code.
 Improved readability: Functions organize code into logical sections.
 Easier maintenance: Changes only need to be made in one place.

Function Parameters and Return Values


Functions can take parameters as inputs and return values as outputs.

Using Parameters: Parameters allow functions to accept values when called.

function greetUser($name) {
echo "Hello, $name!";
}
greetUser("John");
Here, the function greetUser("John"); outputs "Hello, John!".

Default Parameter Values: A default value can be assigned to parameters:

function greetUser($name = "Guest") {


echo "Hello, $name!";
}
greetUser(); // Outputs: Hello, Guest!
Returning Values: A function can return a value using the return statement:

function add($a, $b) {


return $a + $b;
}
$result = add(5, 10);
echo "Sum: $result"; // Outputs: Sum: 15

Variable Scope in PHP


Variable scope determines where a variable can be accessed within a program. PHP supports three types
of scope: Local, Global, and Static.

12 of 19
Internet Programming II

1. Local Scope
Variables declared inside a function are local and cannot be accessed outside it.

function localScope() {
$message = "This is a local variable";
echo $message;
}
localScope();
// echo $message; // This will cause an error

2. Global Scope
Variables declared outside a function have global scope and cannot be accessed inside a function unless
explicitly specified using the global keyword.

$globalVar = "I am global";


function showGlobal() {
global $globalVar;
echo $globalVar;
}
showGlobal(); // Outputs: I am global
Alternatively, PHP provides $GLOBALS array to access global variables:

$globalVar = "I am global";


function showGlobal() {
echo $GLOBALS['globalVar'];
}
showGlobal();

3. Static Scope
Static variables retain their value across multiple function calls.

function staticCounter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
staticCounter(); // Outputs: 1
staticCounter(); // Outputs: 2
staticCounter(); // Outputs: 3

13 of 19
Internet Programming II

Passing Arguments
By default, PHP passes arguments by value, meaning changes made inside the function do not affect the
original variable. Passing by reference allows modifications to persist outside the function.

5. Passing by Value (Default)

function increment($num) {
$num++;
echo "Inside function: $num";
}
$value = 5;
increment($value);
echo "Outside function: $value"; // Outputs: Outside function: 5
The original $value remains unchanged.

6. Passing by Reference

Using the & symbol allows functions to modify the original variable.

function incrementByReference(&$num) {
$num++;
}
$value = 5;
incrementByReference($value);
echo "Outside function: $value"; // Outputs: Outside function: 6

Best Practices for Using Functions


 Use meaningful function names that describe the purpose of the function.
 Keep functions short and focused on a single task.
 Use default parameters to prevent errors when no value is passed.
 Always use the return statement for functions that compute a value.
 Avoid modifying global variables inside functions; instead, pass them as arguments.

Common Errors and Debugging Tips


 Undefined function errors: Ensure function definitions appear before they are called.
 Variable scope issues: Remember that variables declared inside a function are not accessible
outside unless declared as global.
 Incorrect argument count: Ensure the number of parameters matches the function definition.

14 of 19
Internet Programming II

Common Built-in Functions in PHP


PHP provides a rich set of built-in functions for performing various tasks efficiently.

String Functions
strlen("Hello World"); // Returns length of the string
strtoupper("hello"); // Converts to uppercase
strtolower("HELLO"); // Converts to lowercase
str_replace("world", "PHP", "Hello world"); // Replaces text
trim(" text "); // Removes whitespace from both sides

Mathematical Functions
abs(-5); // Returns absolute value (5)
round(4.6); // Rounds to nearest integer (5)
rand(1, 100); // Generates a random number between 1 and 100
max(10, 20, 30); // Returns the largest number (30)
min(10, 20, 30); // Returns the smallest number (10)

Date and Time Functions


date("Y-m-d"); // Returns current date in format YYYY-MM-DD
time(); // Returns current Unix timestamp
strtotime("next Monday"); // Converts text to timestamp

Practice Exercises
1. Create a function to add a new business listing – The function should take business name,
category, and location as parameters and return a confirmation message.
2. Write a function to search for businesses by category – The function should accept a category as
an argument and return a filtered list of businesses.
3. Implement a function to calculate the number of businesses per city – Use an array to store
businesses and group them by city.
4. Develop a function to update business information – The function should accept a business ID
and an associative array of updated details.
5. Pass business data by reference to optimize memory usage – Modify a business listing inside a
function using reference arguments.

15 of 19
Internet Programming II

PHP Arrays
Arrays are fundamental data structures in PHP that allow multiple values to be stored in a single variable.
Arrays help in organizing and manipulating data efficiently, making them essential for dynamic web
applications, such as a Business Directory Application.

Types of Arrays in PHP


PHP supports three types of arrays:

1. Indexed Arrays – Arrays with numeric indexes.


2. Associative Arrays – Arrays with named keys.
3. Multidimensional Arrays – Arrays containing multiple arrays.

1. Indexed Arrays
Indexed arrays store values using numeric indexes that start from zero.

$businesses = ["Cafe Aroma", "Tech Solutions", "Green Market"];


echo $businesses[0]; // Outputs: Cafe Aroma

Using a for loop to iterate over an indexed array:

for ($i = 0; $i < count($businesses); $i++) {


echo $businesses[$i] . "<br>";
}

2. Associative Arrays
Associative arrays use named keys instead of numeric indexes, making them ideal for structured data like
business listings.

$business = [
"name" => "Cafe Aroma",
"category" => "Restaurant",
"location" => "Downtown"
];
echo $business["name"]; // Outputs: Cafe Aroma
Using a foreach loop to iterate over an associative array:

foreach ($business as $key => $value) {


echo "$key: $value <br>";
}

16 of 19
Internet Programming II

3. Multidimensional Arrays
Multidimensional arrays contain multiple arrays inside them, useful for storing complex data structures
like a list of businesses with details.

$directory = [
["name" => "Cafe Aroma", "category" => "Restaurant", "location" =>
"Downtown"],
["name" => "Tech Solutions", "category" => "IT Services", "location" =>
"Uptown"],
["name" => "Green Market", "category" => "Grocery", "location" =>
"Suburb"]
];
echo $directory[1]["name"]; // Outputs: Tech Solutions
Iterating through a multidimensional array:

foreach ($directory as $business) {


echo "Name: " . $business["name"] . " - Category: " .
$business["category"] . "<br>";
}

Commonly Used Array Functions in PHP


PHP provides various built-in functions to manipulate arrays efficiently.

Adding and Removing Elements


array_push($businesses, "Blue Bakery"); // Adds an item
array_pop($businesses); // Removes the last item
array_unshift($businesses, "City Gym"); // Adds an item at the
beginning
array_shift($businesses); // Removes the first item
Sorting Arrays
Sorting indexed and associative arrays can help organize business listings.

sort($businesses); // Sorts in ascending order


rsort($businesses); // Sorts in descending order
asort($business); // Sorts associative arrays by values
ksort($business); // Sorts associative arrays by keys
Searching and Filtering Arrays

$position = array_search("Tech Solutions", $businesses);


echo "Found at index: " . $position;

17 of 19
Internet Programming II

Filtering businesses by category:

$filtered = array_filter($directory, function ($biz) {


return $biz["category"] == "Restaurant";
});
print_r($filtered);

Merging and Splitting Arrays


$moreBusinesses = ["Auto Repair", "Bookstore"];
$allBusinesses = array_merge($businesses, $moreBusinesses); // Combines
arrays
Splitting an array into chunks:

$chunks = array_chunk($allBusinesses, 2);


print_r($chunks);

Checking If a Key or Value Exists in an Array


if (array_key_exists("category", $business)) {
echo "Category: " . $business["category"];
}
Checking if a value exists:

if (in_array("Tech Solutions", $businesses)) {


echo "Tech Solutions is listed.";
}

Getting Keys and Values from an Array


$keys = array_keys($business);
$values = array_values($business);
print_r($keys);
print_r($values);
Counting and Array Length
echo count($businesses); // Returns number of elements in the array

18 of 19
Internet Programming II

Practice Exercises
1. Store a list of business names as an indexed array and display them in a dropdown menu for users to
select.
2. Use an associative array to store business details (name, category, location, contact number) and
display them in a structured format.
3. Implement a search function that takes a category as input and filters businesses in that category.
4. Sort business listings alphabetically by name and display them in a user-friendly table format.
5. Group businesses by location using multidimensional arrays and display businesses grouped under
each city.
6. Create a function to update business details by modifying values in an associative array.
7. Use array_column() to extract all business names from the directory and display them as a simple
list.
8. Remove duplicate business entries using array_unique() and display only unique businesses.
9. Use array_chunk() to paginate business listings and show only a limited number of businesses per
page.
10. Check if a business is already listed before adding it to the directory using in_array() and provide
appropriate feedback to users.

19 of 19

You might also like