Unit 2 Question Bank
Unit 2 Question Bank
Unit-II
1. Creating function
a. Passing functions Some Data
b. Creating functions in PHP
c. Passing array to functions
d. Passing by reference
e. Using Default Arguments
f. Passing Variable Numbers of Arguments
g. Returning Data from Functions
h. Returning Arrays
i. Returning Lists
j. Returning References
k. Variable scope
$value = 5;
double($value); // $value is now 10
Explanation of program:
In this program, the double() function takes a parameter by reference. When the function
modifies the value of $num, it directly affects the original variable $value.
e. Using Default Arguments: You can set default values for function parameters. If an
argument is not provided during the function call, the default value will be used.
Example:
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!
Explanation of program:
The greet() function is defined with a default value for the $name parameter. If no argument
is provided, it uses the default value. Otherwise, it uses the provided argument.
f. Passing Variable Numbers of Arguments: PHP allows you to work with variable numbers of
arguments using functions like func_num_args(), func_get_arg(), and func_get_args().
Example:
function sum() {
$total = 0;
foreach (func_get_args() as $num) {
$total += $num;
PROGRAMMING IN PHP QUESTION BANK
}
return $total;
}
g. Returning Data from Functions: Functions can return values using the return statement.
This is useful when you want to perform a computation and pass the result back to the calling
code.
Example:
function square($num) {
return $num * $num;
}
$squaredValue = square(5); // $squaredValue now holds the value 25
Explanation of program:
The square() function calculates the square of the given number and returns the result. The
returned value is assigned to the variable $squaredValue.
h. Returning Arrays: Functions can return arrays, allowing you to encapsulate and organize
data for easier processing.
Example:
function getColors() {
return array("red", "green", "blue");
}
$colors = getColors(); // $colors holds the array ["red", "green", "blue"]
Explanation of program:
The getColors() function returns an array of colors, which is assigned to the variable $colors
PROGRAMMING IN PHP QUESTION BANK
i. Returning Lists: Although PHP doesn't have a built-in "list" type, you can return multiple
values from a function as an array and then use list assignment to extract the values.
Example:
function getCoordinates() {
return array(10, 20);
}
list($x, $y) = getCoordinates(); // $x is 10, $y is 20
Explanation of program:
The getCoordinates() function returns an array, and the list() construct is used to assign its
values to individual variables.
j. Returning References: You can return references from functions using the & symbol. This
allows you to modify the original variable's value directly.
Example:
function &getReference(&$var) {
return $var;
}
$value = 42;
$ref = &getReference($value); // $ref now references $value
$ref = 55; // $value is now 55
Explanation of program:
The &getReference() function returns a reference to the variable passed to it. Changes made
to $ref also affect the original variable $value.
k. Variable Scope: Variables have different scopes depending on where they are defined. A
variable declared inside a function is local to that function, while a variable declared outside
of any function has a global scope.
Example:
$globalVar = 10;
function example() {
$localVar = 5;
PROGRAMMING IN PHP QUESTION BANK
example();
echo $localVar; // Error: $localVar is not defined in this scope
echo $globalVar; // Outputs: 10
Explanation of program: In this program, we have a global variable $globalVar and a
local variable $localVar within the example()
a. Handling Text Fields: Text fields are input elements where users can enter single-line text.
In PHP, you can access the data submitted through text fields using the $_POST or $_GET
superglobal arrays, depending on the form's submission method.
Example Program:
html
<form method="post" action="process.php">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
In process.php:
$username = $_POST['username'];
echo "Hello, $username!";
Explanation of program: In this program, a form with a text input field is created.
When the user enters their username and clicks the "Submit" button, the data is sent to
process.php using the POST method. The PHP script then retrieves the submitted
username from the $_POST superglobal and echoes a greeting message.
Output: If you enter "Alice" in the text field and submit the form, the output will be:
Hello, Alice!
PROGRAMMING IN PHP QUESTION BANK
b.Handling Text Areas: Text areas are input elements for longer text. They can be accessed
similarly to text fields using $_POST or $_GET.
Example Program:
Html
<form method="post" action="process.php">
<textarea name="message"></textarea>
<input type="submit" value="Submit">
</form>
In process.php :
$message = $_POST['message'];
echo "Your message: $message";
Explanation of program: This program creates a form with a textarea element. When
the user enters a message and submits the form, the data is sent to process.php using
the POST method. The PHP script retrieves the submitted message from $_POST and
echoes it.
Output: If you enter "Hello, world!" in the textarea and submit the form, the output
will be:
Your message: Hello, world!
c. Handling Check Boxes: Check boxes allow users to select multiple options. If checked,
their values are submitted. You can use an array of names for the check boxes to handle
multiple selections.
Example Program:
Html
<form method="post" action="process.php">
<input type="checkbox" name="fruits[]" value="apple"> Apple
<input type="checkbox" name="fruits[]" value="banana"> Banana
<input type="submit" value="Submit">
</form>
In process.php:
$selectedFruits = $_POST['fruits'];
echo "Selected fruits: " . implode(", ", $selectedFruits);
Explanation of the program: This program creates a form with two checkboxes. Users
can select one or both checkboxes. When the form is submitted, the selected
checkboxes' values are sent to process.php. The PHP script retrieves the selected values
from $_POST and echoes them.
Output: If you select both "Apple" and "Banana" checkboxes and submit the form, the
output will be:
Selected fruits: apple, banana
d. Handling Radio Buttons: Radio buttons allow users to select one option from a list. They
are used similarly to check boxes.
Example Program:
PROGRAMMING IN PHP QUESTION BANK
html
<form method="post" action="process.php">
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="submit" value="Submit">
</form>
In process.php:
$gender = $_POST['gender'];
echo "Selected gender: $gender";
Explanation: This program creates a form with two radio buttons for selecting a
gender. When the user selects one of the radio buttons and submits the form, the selected
radio button's value is sent to process.php. The PHP script retrieves the selected value
from $_POST and echoes it.
Output: If you select "Male" and submit the form, the output will be:
Selected gender: male
e. Handling List Boxes: List boxes (select elements) allow users to select one or multiple
options from a list. They can be handled similarly to check boxes.
Example Program:
html
<form method="post" action="process.php">
<select name="colors[]" multiple>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
<input type="submit" value="Submit">
</form>
In process.php:
$selectedColors = $_POST['colors'];
echo "Selected colors: " . implode(", ", $selectedColors);
Explanation: This program creates a form with a multi-select list box for choosing
colors. Users can select one or more colors. When the form is submitted, the selected
colors' values are sent to process.php. The PHP script retrieves the selected values from
$_POST and echoes them.
Output: If you select "Red" and "Green" from the list box and submit the form, the
output will be:
Selected colors: red, green
html
PROGRAMMING IN PHP QUESTION BANK
$password = $_POST['password'];
echo "Entered password: $password";
Explanation of the program: This program creates a form with a password input field.
When the user enters a password and submits the form, the password data is sent to
process.php using the POST method. The PHP script retrieves the submitted password
from $_POST and echoes it.
Output: If you enter "secretpassword" in the password field and submit the form, the
output will be:
Entered password: secretpassword
g. Handling Hidden Controls: Hidden controls are used to store data that is not displayed to
the user. They can be accessed using $_POST or $_GET.
Example Program:
html
<form method="post" action="process.php">
<input type="hidden" name="secret" value="42">
<input type="submit" value="Submit">
</form>
In process.php:
$secretValue = $_POST['secret'];
echo "Secret value: $secretValue";
Explanation: This program creates a form with a hidden input field that holds a secret
value. The value is not displayed to the user. When the form is submitted, the hidden
field's value is sent to process.php. The PHP script retrieves the value from $_POST
and echoes it.
Output: When you submit the form, the output will be:
Secret value: 42
PROGRAMMING IN PHP QUESTION BANK
h. Handling Image Maps: Image maps allow different parts of an image to be linked to
different destinations. The selected area's coordinates can be accessed using $_POST or
$_GET.
Example Program:
html
<img src="image.png" usemap="#map">
<map name="map">
<area shape="rect" coords="0,0,50,50" href="process.php?area=1">
<area shape="rect" coords="50,50,100,100" href="process.php?area=2">
</map>
In process.php:
$selectedArea = $_GET['area'];
echo "Selected area: $selectedArea";
Explanation: This program uses an image with an associated image map. The image
map defines two clickable areas with coordinates. When a user clicks an area, the
process.php script is called with the corresponding area parameter using the GET
method. The PHP script retrieves the selected area from $_GET and echoes it.
Output: If you click on the first area of the image and the URL becomes
process.php?area=1, the output will be:
Selected area: 1
i. Handling File Uploads: File uploads use the $_FILES superglobal to access uploaded files.
The enctype attribute must be set to "multipart/form-data" in the form.
Example Program:
Html
<form method="post" action="process.php" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
In process.php:
$uploadedFile = $_FILES['file'];
echo "Uploaded file name: " . $uploadedFile['name'];
Explanation: This program demonstrates how to create a form for file uploads. The
form includes an input element with the type "file". The form's enctype attribute is set
to "multipart/form-data" to support file uploads. When the form is submitted, the
PROGRAMMING IN PHP QUESTION BANK
uploaded file's information is accessible in the $_FILES superglobal. The PHP script
retrieves the uploaded file's name from the $_FILES array and echoes it.
Output: If you upload a file named "sample.txt", the output will be:
Uploaded file name: sample.txt
j. Handling Buttons: Buttons can be used to submit forms or trigger JavaScript functions.
Example Program:
Html
<form method="post" action="process.php">
<input type="submit" name="submitButton" value="Submit">
</form>
process.php:
if (isset($_POST['submitButton'])) {
echo "Button submitted!";
}
Explanation: This program demonstrates the use of buttons in forms. The form
includes an input element with the type "submit" and a name "submitButton". When
the user clicks the "Submit" button, the form is submitted to process.php using the
POST method. In process.php, the presence of the "submitButton" key in $_POST is
checked using isset(). If the button was clicked, the script echoes a message.
Output: When you click the "Submit" button in the form, the output will be:
Button submitted!
Example Program:
echo "Server IP Address: " . $_SERVER['SERVER_ADDR'];
Explanation: The program retrieves the server's IP address from the $_SERVER
superglobal and echoes it.
b. HTTP Headers:
Definition: HTTP headers are part of the HTTP response and request messages that
provide additional information about the data being transferred. They can be accessed
using the $_SERVER superglobal.
Example Program:
$contentType = $_SERVER['HTTP_CONTENT_TYPE'];
echo "Content Type: $contentType";
$contentType = $_SERVER['HTTP_CONTENT_TYPE'];
echo "Content Type: $contentType";
Explanation: The program retrieves the "Content-Type" header from the $_SERVER
superglobal and echoes its value.
Output: If the "Content-Type" header is "application/json", the output will be:
Content Type: application/json
Explanation: The program retrieves the user's browser user agent from the
$_SERVER superglobal and echoes it.
Output: The output will display the user agent string, indicating the browser and its
version.
d. Performing Data Validation:
PROGRAMMING IN PHP QUESTION BANK
Definition: Data validation is the process of ensuring that data provided by users is correct,
complete, and appropriate. It helps prevent errors and security vulnerabilities.
Example Program:
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address";
} else {
echo "Invalid email address";
}
Explanation: The program validates an email address submitted through a form using
the filter_var() function with the FILTER_VALIDATE_EMAIL filter.
Output: If a valid email address is submitted, the output will be:
Valid email address
f. Requiring Data:
Definition: Requiring data ensures that certain fields are filled out before proceeding.
Example Program:
if (isset($_POST['name']) && isset($_POST['email'])) {
echo "Data provided";
} else {
echo "Please provide name and email";
}
Explanation: The program checks if both "name" and "email" fields are set and echoes
a message accordingly.
Output: If both "name" and "email" fields are provided, the output will be:
Data provided
g. Requiring Text:
PROGRAMMING IN PHP QUESTION BANK
Definition: Requiring text ensures that a field contains non-empty text before
proceeding.
Example Program:
if (strlen(trim($_POST['comment'])) > 0) {
echo "Comment provided";
} else {
echo "Please provide a comment";
}
Explanation: The program trims and checks the length of the "comment" field
submitted through a form, echoing a message based on whether it's non-empty.
Output: If a non-empty comment is provided, the output will be:
Comment provided
Explanation: The program demonstrates both client-side and server-side validation for
a "quantity" field. Client-side validation is performed using JavaScript before
submitting the form, and server-side validation is done in process.php.
Output:
If you enter a valid quantity greater than 0 and submit the form, the output will
be:
Valid quantity
If you enter 0 or a negative value for the quantity and submit the form, the output
will be:
Invalid quantity