Web Framework and Services — Study Notes

Unit 01

Core PHP Programming

10 Questions 5 Marks Each Web Framework and Services
01
5 Marks Question

Explain PHP Data Types and Operators

PHP Data Types

A data type specifies the type of value stored in a variable. PHP is loosely typed, so we do not need to explicitly declare the data type of a variable; PHP determines it automatically.

PHP supports 8 main data types.

Data Type Meaning Example
IntegerWhole numbers$a = 10;
Float (Double)Numbers with decimal points$a = 10.5;
StringSequence of characters$name = "PHP";
BooleanRepresents TRUE or FALSE$x = true;
ArrayStores multiple values$a = array(10,20,30);
ObjectInstance of a class$obj = new Student();
NULLRepresents a variable with no value$a = NULL;
ResourceReference to an external resource, such as a file or database connection$file = fopen(...);

For example, integers represent whole numbers, while floating-point numbers represent real or decimal numbers.

PHP Operators

Operators are symbols used to perform operations on variables and values. The important types of PHP operators are:

01
Arithmetic

Symbols: +, -, *, /, %

Used for mathematical calculations.

02
Assignment

Symbols: =, +=, -=, *=, /=, %=

Used to assign or modify values.

03
Comparison

Symbols: ==, ===, !=, >, <, >=, <=

Compare two values and return TRUE or FALSE.

04
Increment / Decrement

Symbols: ++$a, $a++, --$a, $a--

Increase or decrease a variable by 1.

05
String

Symbols: .

Joins / concatenates strings, for example: "Hello " . "PHP" → Hello PHP.

06
Logical

Symbols: &&, ||, !

Used to combine or reverse conditions.

In short Data types define what kind of data is stored, while operators define what operations are performed on that data.
02
5 Marks Question

Explain Arrays in PHP

An array in PHP is used to store multiple values in a single variable. PHP supports different types of arrays and provides built-in functions for sorting and managing array data.

Types of Arrays in PHP

There are three main types of arrays:

Indexed Array
Stores values using numeric indexes starting from 0.
<?php
$names = array("Fabio", "Klevi", "John");

echo $names[0];
?>
Output: Fabio
Associative Array
Uses named keys instead of numeric indexes.
<?php
$namesAge = array(
    "Fabio" => "20",
    "Klevi" => "16",
    "John" => "43"
);

echo $namesAge["Fabio"];
?>
Output: 20
Multidimensional Array
An array whose elements are themselves arrays.
<?php
$socialNetworks = array(
    array("Facebook", "Feb", 21),
    array("Twitter", "Dec", 2),
    array("Instagram", "Aug", 15)
);
?>

Common Array Functions

PHP provides several built-in functions for working with arrays.

Function Purpose
sort()Sorts values in ascending order and creates new numeric indexes.
asort()Sorts by values while preserving keys.
ksort()Sorts an associative array by keys.
array_merge()Combines two or more arrays into one array.
In short PHP arrays allow multiple values to be stored in one variable and are mainly classified as Indexed, Associative, and Multidimensional arrays.
03
5 Marks Question

Explain PHP Tags

PHP tags are used to indicate where PHP code starts and ends in a file. The opening tag tells the server that the code following it is PHP code.

PHP provides the following types of tags:

Standard Tag
The most commonly used and recommended PHP tag. It is universally supported.
<?php
echo "Hello";
?>
Short Echo Tag
Used to display output quickly. It is equivalent to a standard echo block.
<?= "Hello"; ?>
Short Tag
A shorter form of the PHP tag. It is not recommended because short tags may be disabled on some servers.
<?
echo "Hello";
?>
Script Tag
An old method of writing PHP code and rarely used now.
<script language="php">
echo "Hello";
</script>
Conclusion: The standard <?php ... ?> tag is the recommended method because it is universally supported.
04
5 Marks Question

Explain the Filter Function in PHP

PHP provides the Filter Extension to validate and sanitize data. It helps developers handle user input safely without writing complex regular expressions.

Filtering is mainly used for two purposes: validation checks whether data is in the required format, and sanitization removes or converts unwanted or unsafe characters from data.

1. filter_var() Function

The filter_var() function is used to filter a specific variable.

Syntax: filter_var($variable, $filter, $options);

<?php
$email = "abc@gmail.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid Email";
} else {
    echo "Invalid Email";
}
?>

Here, FILTER_VALIDATE_EMAIL checks whether the given value has a valid email format.

2. filter_input() Function

The filter_input() function directly gets data from superglobals such as $_GET and $_POST and filters it.

Syntax: filter_input($type, $variable_name, $filter);

For example: $age = filter_input(INPUT_POST, "age", FILTER_VALIDATE_INT);

Common Validation Filters

FilterPurpose
FILTER_VALIDATE_EMAILChecks for a valid email
FILTER_VALIDATE_INTChecks for a valid integer
FILTER_VALIDATE_URLChecks for a valid URL

Common Sanitization Filters

FilterPurpose
FILTER_SANITIZE_EMAILRemoves invalid characters from an email
FILTER_SANITIZE_NUMBER_INTKeeps only digits, + and -
FILTER_SANITIZE_SPECIAL_CHARSEncodes special HTML characters
Conclusion PHP filter functions are useful for validating and sanitizing user input, which makes input safer and ensures that the application receives data in the expected format.
05
5 Marks Question

Explain Validation in PHP

Validation in PHP is the process of checking whether user input meets the expected format, type, or rules before it is processed or stored. It helps maintain data accuracy, integrity, and application security.

For example, validation can check whether an email address is properly formatted, whether a name has the correct length, whether a number is within a specified range, or whether a required field is empty.

Types of Input Validation

Format Validation
Checks whether data follows the required format or pattern.
Length Validation
Checks the minimum, maximum, or exact length of input.
Range Validation
Checks whether a value falls within an acceptable range.
Type Validation
Checks whether the input is of the expected data type.
Content Validation
Examines input for malicious or inappropriate content.

Validation Using PHP Filters

PHP provides built-in validation filters such as FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT, and FILTER_VALIDATE_URL.

<?php
$email = "abc@gmail.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid Email";
} else {
    echo "Invalid Email";
}
?>
Importance of Validation: Validation protects applications from security problems such as SQL injection and XSS, prevents incorrect data from entering the database, and helps enforce application rules.
Conclusion Validation ensures that user-provided data is correct, relevant, and safe before it is processed or stored.
06
5 Marks Question

Explain Type Juggling in PHP with Example

Type Juggling in PHP is the automatic conversion of one data type into another when required. PHP is a loosely typed language, so it is not necessary to explicitly declare the datatype of a variable. PHP automatically determines and converts the type when an operation requires it.

Example

<?php

$a = 10;      // Integer
$b = "20";    // String

$c = $a + $b; // PHP automatically converts "20" to integer

echo $c;

?>
Output: 30

Here, $a is an integer with value 10 and $b is a string containing "20". When $a + $b is performed, PHP automatically converts the string "20" into an integer, so the addition becomes 10 + 20, producing 30. This automatic conversion of the string into an integer is called Type Juggling.

Type Juggling vs Type Casting

Type juggling should not be confused with type casting:

01
Type Juggling

PHP performs the conversion automatically when required.

02
Type Casting

The programmer explicitly forces a value into a particular type using a cast operator such as (int), (float), (string) or (bool).

$value = "25";
$number = (int)$value;

Here, (int) explicitly converts the string to an integer.

In short Type Juggling makes PHP flexible by allowing it to automatically convert values between data types during operations.
07
5 Marks Question

Explain Variable Scope in PHP with Example

Variable scope in PHP defines where a variable can be accessed in a PHP program. Variables declared inside or outside functions behave differently depending on their scope. The main types are Local Scope and Global Scope.

01
Local Scope

A variable declared inside a function is called a local variable. It can be accessed only within that function and cannot normally be accessed outside it.

<?php
function test()
{
    $num = 100; // Local variable
    echo "Inside Function: " . $num;
}

test();

echo "<br>";
echo $num; // Error
?>
Output:
Inside Function: 100
Undefined variable: num

Here, $num is created inside the test() function, so it exists only within that function. Trying to access it outside the function produces an error. Local variables are also destroyed after the function execution ends.

02
Global Scope

A variable declared outside all functions is called a global variable. It can normally be accessed outside functions. To access it inside a function, PHP provides the global keyword.

<?php

$name = "BCA"; // Global variable

function display()
{
    global $name;
    echo "Name: " . $name;
}

display();

?>
Output: Name: BCA

Here, $name is declared outside the function. The statement global $name; allows the function to access the global variable.

Accessing Global Variables using $GLOBALS: PHP also stores global variables in a special $GLOBALS array, which can be used to access global variables inside a function.

Summary

ScopeWhere DeclaredWhere Accessible
LocalInside a functionOnly inside that function
GlobalOutside all functionsOutside functions; inside using global or $GLOBALS
Conclusion Variable scope controls the visibility and accessibility of variables in PHP. Understanding local and global scope helps prevent unwanted access and makes programs easier to organize and maintain.
08
5 Marks Question

Differentiate Between include and require Statements in PHP

Both include and require are PHP statements used to include the contents of another PHP file into the current script. They are useful for reusing common code such as functions, headers, configuration files, etc.

Aspectincluderequire
Missing FileGenerates a warning; the script generally continues executing.Generates a fatal error; script execution stops.
SuitabilitySuitable when the included file is optional.Suitable when the included file is essential for the application.
Use CaseUsed when failure to include the file should not stop the entire program.Used when the program cannot work correctly without the file.

Example of include

<?php
include "header.php";

echo "Welcome to the website";
?>

If header.php is missing, PHP gives a warning, but the remaining code can continue executing.

Example of require

<?php
require "config.php";

echo "Database application started";
?>

If config.php is missing, execution stops because the required file is essential.

include  -> Warning     -> Script continues
require  -> Fatal error -> Script stops
Conclusion The main difference is how PHP handles a missing file. Therefore, use include for optional files and require for essential files such as configuration or database connection files.
09
5 Marks Question

Differentiate Between echo and print Statements in PHP

Both echo and print are used in PHP to display output on the screen.

Aspectechoprint
ArgumentsCan output multiple strings/values separated by commas.Accepts only one argument.
Return ValueDoes not return a value.Returns the value 1 after successful execution.
SpeedGenerally considered slightly faster, as it does not return a value.Slightly slower, as it returns a value.
ParenthesesOptional.Also optional.

Example using echo

<?php
$name = "Rahul";
$age = 20;

echo "Name: ", $name, " Age: ", $age;
?>
Output: Name: Rahul Age: 20

Example using print

<?php
$name = "Rahul";

print "Name: " . $name;
?>
Output: Name: Rahul

Key Difference: echo can accept multiple arguments and does not return a value, while print accepts one argument and returns 1.

Conclusion Both can be used for displaying output, but echo is generally preferred when simply displaying output.
10
5 Marks Question

Explain Array Operations: sort(), asort(), ksort(), array_merge()

PHP provides several built-in functions for sorting and combining arrays. The important operations are sort(), asort(), ksort(), and array_merge().

01
sort()

Sorts an array in ascending order according to its values. It also re-indexes the array with numeric keys starting from 0.

$numbers = [40, 10, 30, 20];

sort($numbers);

print_r($numbers);

Output:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)
02
asort()

Sorts an array in ascending order according to its values, but preserves the original keys.

$marks = [
    "Rahul" => 70,
    "Amit" => 90,
    "Neha" => 80
];

asort($marks);

print_r($marks);

Output:
Array
(
    [Rahul] => 70
    [Neha] => 80
    [Amit] => 90
)

Here, the values are sorted, but the student names remain associated with their original values.

03
ksort()

Sorts an associative array according to its keys in ascending order.

$marks = [
    "Neha" => 80,
    "Amit" => 90,
    "Rahul" => 70
];

ksort($marks);

print_r($marks);

Output:
Array
(
    [Amit] => 90
    [Neha] => 80
    [Rahul] => 70
)

Here, the keys (names) are sorted alphabetically while their corresponding values remain associated with them.

04
array_merge()

Combines two or more arrays into a single array.

$array1 = ["Apple", "Banana"];
$array2 = ["Mango", "Orange"];

$result = array_merge($array1, $array2);

print_r($result);

Output:
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Mango
    [3] => Orange
)

For arrays with numeric keys, the resulting array is re-indexed starting from 0.

Summary

FunctionOperationKey Behaviour
sort()Sorts by values in ascending orderRe-indexes numeric keys
asort()Sorts by values in ascending orderPreserves keys
ksort()Sorts by keys in ascending orderPreserves key-value relationship
array_merge()Combines multiple arraysNumeric keys are re-indexed
In short sort() sorts values and resets keys, asort() sorts values while preserving keys, ksort() sorts by keys, and array_merge() combines arrays.