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

AWDP

Uploaded by

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

AWDP

Uploaded by

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

UNIT:1

1. What are the main new features introduced in HTML5?

Answer: The main new features introduced in HTML5 are:

1. Semantic Elements: New tags like <header>, <footer>, <article>, <section>, etc., provide
better structure and meaning to the content.

2. Multimedia Support: HTML5 supports audio and video embedding directly through <audio>
and <video> tags.

3. Graphics: HTML5 introduces the <canvas> element for 2D drawing and supports SVG
(Scalable Vector Graphics).

4. Form Enhancements: New input types such as email, date, number, and attributes like
placeholder, autofocus, etc., improve form handling.

5. APIs: HTML5 includes APIs such as Geolocation, Web Storage (localStorage and
sessionStorage), Web Workers, and WebSockets.

6. Offline Support: Web applications can work offline using the Application Cache.

2. Explain the basic structure of HTML documents (webpage structure).

Answer: The basic structure of an HTML document includes:

html

Copy code

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Page Title</title>

</head>

<body>

<header>

<!-- Header content -->

</header>

<nav>

<!-- Navigation links -->


</nav>

<main>

<section>

<!-- Main content -->

</section>

</main>

<footer>

<!-- Footer content -->

</footer>

</body>

</html>

 <!DOCTYPE html>: Defines the document as HTML5.

 <html>: The root element.

 <head>: Contains metadata like <title>, <meta>, and links to CSS/JS.

 <body>: Contains visible content like text, images, and other elements.

3. Explain the following HTML tags with proper examples. <img>, <a>, <select>, <span>, <input>,
<textarea>, <div>

Answer:

 <img>: Used to display images.

html

Copy code

<img src="image.jpg" alt="Sample Image" width="200" height="100">

 <a>: Defines a hyperlink.

html

Copy code

<a href="https://example.com" target="_blank">Visit Example</a>

 <select>: Creates a dropdown list.

html

Copy code

<select>

<option value="1">Option 1</option>


<option value="2">Option 2</option>

</select>

 <span>: An inline container used for styling.

html

Copy code

<p>This is a <span style="color: red;">highlighted</span> text.</p>

 <input>: Defines input fields.

html

Copy code

<input type="text" placeholder="Enter your name">

 <textarea>: Creates a multi-line text input.

html

Copy code

<textarea rows="4" cols="50">Enter text here</textarea>

 <div>: A block-level container used for grouping elements.

html

Copy code

<div style="background-color: lightgray;">Content goes here</div>

4. Write HTML code to display the following irregular table.

Answer:

<!DOCTYPE html>

<html>

<head>

<title>Irregular Table</title>

</head>

<body>

<table border="1" cellspacing="0" cellpadding="5">

<tr>

<td colspan="4">A</td>

<td colspan="3">B</td>

<td rowspan="3">J</td>
</tr>

<tr>

<td rowspan="2">C</td>

<td colspan="2">D</td>

<td>E</td>

<td rowspan="2">G</td>

<td>H</td>

</tr>

<tr>

<td>K</td>

<td>M</td>

<td>N</td>

<td>I</td>

</tr>

<tr>

<td colspan="2">L</td>

<td>P</td>

<td>O</td>

<td>I</td>

<td>H</td>

</tr>

</table>

</body>

</html>

5. What is a meta tag? How is it useful for search engines? OR Explain all the Meta Tags with
examples.

Answer: A meta tag is an HTML tag that provides metadata (data about data) about a webpage.
Meta tags are placed inside the <head> section and are not displayed on the webpage. They help
search engines understand the content of the page and improve SEO (Search Engine Optimization).

Examples of Meta Tags:

 <meta charset="UTF-8">: Defines the character set for the HTML document.
 <meta name="description" content="A webpage about HTML basics">: Provides a
description of the page, useful for search engines to understand the page's content.

 <meta name="keywords" content="HTML, CSS, JavaScript">: Lists keywords related to the


page's content, helping search engines categorize the page.

 <meta name="author" content="Yash Bhavsar">: Specifies the author of the page.

 <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the


page is responsive and looks good on all devices.

Usage for Search Engines: Meta tags like description and keywords help search engines determine
the relevance of a webpage for search queries, improving the page's visibility in search results.

6. What is CSS? What are the benefits of CSS?

Answer:

CSS (Cascading Style Sheets) is a stylesheet language used to control the appearance of HTML
elements on a webpage. It defines styles like colors, fonts, layouts, and spacing.

Benefits of CSS:

1. Separation of Content and Design: HTML handles the content, while CSS manages the
design, making the code cleaner and easier to maintain.

2. Reusability: Styles defined in a single CSS file can be reused across multiple HTML pages.

3. Improved Page Load Speed: CSS reduces the amount of HTML code, making pages load
faster.

4. Responsive Design: CSS media queries allow websites to adapt to different screen sizes and
devices.

7. Explain types of CSS with examples.

Answer: The three types of CSS are:

1. Inline CSS: Styles are applied directly to HTML elements using the style attribute.

html

Copy code

<p style="color: red;">This is an inline styled paragraph.</p>

2. Internal CSS: Styles are defined within a <style> tag inside the <head> section of the HTML
document.

html

Copy code

<head>
<style>

p { color: blue; }

</style>

</head>

3. External CSS: Styles are defined in an external file (e.g., styles.css) and linked to the HTML
document using the <link> tag.

html

Copy code

<head>

<link rel="stylesheet" href="styles.css">

</head>

8. Explain Class and ID Selector in CSS with examples.

Answer:

 Class Selector (.): Used to select elements with a specific class attribute. Multiple elements
can share the same class.

html

Copy code

<style>

.highlight { color: red; }

</style>

<p class="highlight">This is a highlighted paragraph.</p>

 ID Selector (#): Used to select a single element with a unique ID attribute. Only one element
should have a particular ID.

html

Copy code

<style>

#header { background-color: lightblue; }

</style>

<div id="header">This is the header</div>

9. What is the CSS box model? Describe its components.


Answer:

The CSS Box Model is a layout model that defines the structure of elements on a webpage. It consists
of the following components:

1. Content: The innermost part where text and images appear.

2. Padding: Space between the content and the border.

3. Border: The edge surrounding the padding and content.

4. Margin: The outermost space around the element that separates it from other elements.

Example:

css

Copy code

div {

width: 200px;

padding: 10px;

border: 5px solid black;

margin: 20px;

10. What is the use of z-index property in CSS? How can you create a hover effect on an image
using CSS?

Answer:

z-index Property: The z-index property controls the stacking order of elements on a web page.
Elements with a higher z-index value will appear in front of those with lower values. It only works on
positioned elements (position: absolute;, relative;, fixed;).

Example:

html

Copy code

<div style="position: absolute; z-index: 1;">Element 1</div>

<div style="position: absolute; z-index: 2;">Element 2 (Appears on top)</div>

Creating a Hover Effect on an Image Using CSS: The hover effect changes the style of an image when
the user hovers over it.

Example:

html

Copy code

<style>
img:hover {

opacity: 0.7; /* Changes image transparency */

transform: scale(1.1); /* Enlarges the image */

</style>

<img src="image.jpg" alt="Sample Image" width="200px">

11. Explain the use of Media Query in CSS.

Answer:

Media Query is a CSS technique used to apply styles based on the device's characteristics, such as
screen size, resolution, orientation, etc. It helps create responsive web designs that adapt to different
devices (e.g., desktops, tablets, mobile phones).

Example:

css

Copy code

/* Default style */

body {

background-color: white;

/* Style for screens with a max width of 600px */

@media only screen and (max-width: 600px) {

body {

background-color: lightblue;

In this example, the background color changes to light blue for devices with a screen width of 600px
or less.

12. What is JavaScript? What are the benefits of JavaScript?

Answer:
JavaScript is a high-level, interpreted scripting language commonly used to make web pages
interactive. It runs on the client-side (browser) and can manipulate HTML and CSS to provide
dynamic content.

Benefits of JavaScript:

1. Interactivity: Adds interactive elements to websites, such as animations and form


validations.

2. Rich User Interface: Enables features like drag-and-drop, sliders, and responsive menus.

3. Fast Execution: Runs directly in the browser without server interaction, providing quick
responses to user actions.

4. Versatility: Works on both client-side and server-side (e.g., Node.js) applications.

13. What are the different types of loops available in JavaScript? Provide examples.

Answer:

JavaScript offers several loops for iterating through data:

1. for Loop: Repeats a block of code a specific number of times.

javascript

Copy code

for (let i = 0; i < 5; i++) {

console.log(i); // Outputs 0 to 4

2. while Loop: Executes code as long as a specified condition is true.

javascript

Copy code

let i = 0;

while (i < 5) {

console.log(i); // Outputs 0 to 4

i++;

3. do...while Loop: Executes code at least once and then repeats while the condition is true.

javascript

Copy code

let i = 0;
do {

console.log(i); // Outputs 0 to 4

i++;

} while (i < 5);

4. for...of Loop: Iterates over iterable objects (e.g., arrays, strings).

javascript

Copy code

const array = [1, 2, 3];

for (let value of array) {

console.log(value); // Outputs 1, 2, 3

5. for...in Loop: Iterates over object properties.

javascript

Copy code

const object = {a: 1, b: 2};

for (let key in object) {

console.log(key); // Outputs 'a' and 'b'

This completes the remaining questions from the previous set. Let me know if you'd like me to
proceed further!

14. What is the purpose of functions in JavaScript? How do you define and call them?

Answer:

Purpose of Functions in JavaScript: Functions are reusable blocks of code designed to perform
specific tasks. They help organize code, reduce redundancy, and make it easier to maintain.

Defining a Function: A function is defined using the function keyword, followed by the function
name, parentheses (), and a block of code {}.

Example:

javascript

Copy code

function greet(name) {

console.log("Hello, " + name);

}
Calling a Function: To execute the function, use its name followed by parentheses, passing any
required arguments.

Example:

javascript

Copy code

greet("Yash"); // Outputs: Hello, Yash

15. What are built-in functions in JavaScript? Provide examples of any three.

Answer:

Built-in Functions are pre-defined functions in JavaScript that perform common tasks.

Examples:

1. parseInt(): Converts a string into an integer.

javascript

Copy code

let number = parseInt("123");

console.log(number); // Outputs: 123

2. Math.random(): Returns a random number between 0 (inclusive) and 1 (exclusive).

javascript

Copy code

let randomNum = Math.random();

console.log(randomNum); // Outputs: A random decimal number

3. alert(): Displays an alert box with a specified message.

javascript

Copy code

alert("This is an alert!"); // Displays an alert box

16. How can you manipulate the DOM dynamically using JavaScript?

Answer:

DOM (Document Object Model) Manipulation allows JavaScript to dynamically modify the content,
structure, and style of web pages.

Examples of DOM Manipulation:


1. Accessing Elements: Using methods like getElementById, getElementsByClassName,
querySelector.

javascript

Copy code

let element = document.getElementById("header");

2. Modifying Content: Changing the text or HTML of an element.

javascript

Copy code

element.innerHTML = "New Content";

3. Changing Styles: Updating the CSS styles of an element.

javascript

Copy code

element.style.color = "blue";

4. Creating New Elements: Adding new elements to the page.

javascript

Copy code

let newElement = document.createElement("p");

newElement.textContent = "This is a new paragraph.";

document.body.appendChild(newElement);

17. Describe how you would use regular expressions to validate an email address in JavaScript.

Answer:

Regular expressions (regex) are patterns used to match character combinations in strings, commonly
used for validation.

Example of Email Validation Using Regex:

javascript

Copy code

function validateEmail(email) {

const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

return regex.test(email);

}
console.log(validateEmail("[email protected]")); // Outputs: true

console.log(validateEmail("invalid-email")); // Outputs: false

In this example, regex.test(email) checks if the email matches the specified pattern.

18. Explain the use of Bootstrap’s container, row, and col classes.

Answer:

Bootstrap's grid system is built on a responsive layout structure that utilizes three main classes:
container, row, and col.

1. Container:

o Definition: The .container class creates a fixed-width container that provides


responsive margins. It centers the content and aligns it within the viewport.

o Usage:

 Use .container for a standard fixed-width layout.

 Use .container-fluid for a full-width container that spans the entire width of
the viewport.

2. Row:

o Definition: The .row class is used to create a horizontal group of columns. It ensures
that columns within it are properly aligned and spaced.

o Usage:

 A .row should always be placed inside a .container or .container-fluid to


maintain the grid structure.

 It also helps in clearing floats within the grid.

3. Col:

o Definition: The .col classes define the actual columns in the grid. Bootstrap uses a
12-column layout, allowing developers to specify how many columns an element
should span.

o Usage:

 Classes like .col-4, .col-md-6, etc., can be used to define responsive column
widths for different screen sizes.

 They can be combined to create complex layouts (e.g., <div class="col-6">


for a half-width column).

19. What is the purpose of Bootstrap’s utility classes? Provide examples of any three.

Answer:

Purpose: Bootstrap’s utility classes provide quick and easy ways to apply CSS styles directly to HTML
elements without writing custom CSS. They enhance development speed and maintain consistency
across the application.
Examples:

1. Margin and Padding:

o Class: .m-3 or .p-3

o Usage:

 .m-3 applies a margin of 1rem (16px) to all sides of an element.

 .p-3 applies padding of 1rem to all sides.

2. Text Color:

o Class: .text-primary

o Usage:
 This class applies the primary theme color to the text, changing its color
based on Bootstrap’s theme settings.

3. Display:

o Class: .d-none or .d-block

o Usage:

 .d-none hides an element, while .d-block displays it as a block element.


These classes help in managing the visibility of elements responsively.

20. How can you use Bootstrap to create a modal or popup?

Answer:

Creating a Modal with Bootstrap:

1. HTML Structure:

o Use the following HTML to define a modal. It includes a button to trigger the modal
and the modal itself:

html

Copy code

<!-- Button trigger modal -->

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-


target="#exampleModal">

Launch demo modal

</button>

<!-- Modal -->

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel"


aria-hidden="true">
<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>

<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

</div>

<div class="modal-body">

This is the modal body content.

</div>

<div class="modal-footer">

<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>

<button type="button" class="btn btn-primary">Save changes</button>

</div>

</div>

</div>

</div>

2. JavaScript:

o Bootstrap modals require JavaScript for the toggle functionality. Ensure that you
include the Bootstrap JS library in your project:

html

Copy code

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

3. Initialization:

o The modal is triggered by the button, which uses data-bs-toggle="modal" and data-
bs-target="#exampleModal" attributes to specify the modal to open.

This structure allows you to easily create modals with Bootstrap’s predefined styles and
functionalities, enhancing user interaction in web applications.

UNIT:2
21. What is the basic syntax of PHP? How do you include comments in PHP code?

Answer:

Basic Syntax:

 PHP code is embedded within HTML using the <?php ... ?> tags. The PHP code is executed on
the server, and the result is sent to the client's browser.

Example:

php

Copy code

<?php

echo "Hello, World!";

?>

Including Comments:

 PHP supports both single-line and multi-line comments.

1. Single-line comment: Use // or #.

php

Copy code

// This is a single-line comment

# This is also a single-line comment

2. Multi-line comment: Use /* ... */.

php

Copy code

/* This is a

multi-line comment */

22. Write a program in PHP to find out the factorial of a given number.

Answer:

php

Copy code

<?php

function factorial($number) {

if ($number < 0) {
return "Factorial is not defined for negative numbers.";

} elseif ($number == 0) {

return 1;

} else {

$result = 1;

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

$result *= $i;

return $result;

// Example usage

$number = 5;

echo "Factorial of $number is: " . factorial($number);

?>

23. How do you define a constant in PHP, and what is its purpose?

Answer:

Defining a Constant:

 A constant in PHP is defined using the define() function.

Syntax:

php

Copy code

define("CONSTANT_NAME", value);

Purpose:

 Constants are used to store values that should not change during the script execution. They
provide better readability and maintainability.

Example:

php

Copy code

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

24. What is a static variable in PHP, and how does it differ from a regular variable?

Answer:

Static Variable:

 A static variable is defined using the static keyword within a function. It retains its value
across multiple calls to that function.

Differences:

1. Lifetime:

o Static Variable: Persists across function calls.

o Regular Variable: Loses its value after the function execution completes.

2. Scope:

o Static Variable: Local to the function but retains its value.

o Regular Variable: Local to the function and does not retain its value.

Example:

php

Copy code

function counter() {

static $count = 0; // Static variable

$count++;

echo $count;

counter(); // Output: 1

counter(); // Output: 2

25. How do you use global variables in PHP, and what are the potential issues associated with
them?

Answer:

Using Global Variables:

 A global variable is defined outside of functions and can be accessed inside functions using
the global keyword.

Example:

php
Copy code

$globalVar = "Hello, Global!";

function displayGlobal() {

global $globalVar;

echo $globalVar;

displayGlobal(); // Output: Hello, Global!

Potential Issues:

1. Maintainability: Excessive use of global variables can make code difficult to maintain and
debug.

2. Namespace Conflicts: Global variables can clash with other variable names, leading to
unexpected behavior.

3. Testing Difficulty: Functions that rely heavily on global state can be harder to test.

26. Explain the use of if...elseif...else statements in PHP.

Answer:

Usage:

 The if...elseif...else statements are used for conditional execution of code blocks based on
boolean expressions.

Syntax:

php

Copy code

if (condition1) {

// Code to execute if condition1 is true

} elseif (condition2) {

// Code to execute if condition2 is true

} else {

// Code to execute if none of the conditions are true

Example:

php
Copy code

$score = 85;

if ($score >= 90) {

echo "Grade: A";

} elseif ($score >= 80) {

echo "Grade: B";

} else {

echo "Grade: C";

27. How do switch statements work in PHP? Provide an example.

Answer:

Switch Statement:
 The switch statement evaluates an expression and executes the matching case block. It is an
alternative to multiple if...elseif statements.

Syntax:

php

Copy code

switch (expression) {

case value1:

// Code to execute if expression matches value1

break;

case value2:

// Code to execute if expression matches value2

break;

default:

// Code to execute if no match is found

Example:

php

Copy code
$day = 3;

switch ($day) {

case 1:

echo "Monday";

break;

case 2:

echo "Tuesday";

break;

case 3:

echo "Wednesday";

break;

default:

echo "Invalid day";

28. What are the different types of loops available in PHP, and how do they function?

Answer:

Types of Loops:

1. for Loop:

o Executes a block of code a specified number of times.

o Syntax:

php

Copy code

for (initialization; condition; increment) {

// Code to execute

2. while Loop:

o Executes a block of code while a condition is true.

o Syntax:

php

Copy code
while (condition) {

// Code to execute

3. do...while Loop:

o Executes a block of code once, and then repeats while a condition is true.

o Syntax:

php

Copy code

do {

// Code to execute

} while (condition);

4. foreach Loop:

o Used to iterate over arrays.

o Syntax:

php

Copy code

foreach ($array as $value) {

// Code to execute

29. How does a foreach loop work with arrays in PHP?

Answer:

Foreach Loop:

 The foreach loop is specifically designed to iterate through arrays and is simpler than other
loops for this purpose.

Syntax:

php

Copy code

foreach ($array as $value) {

// Code to execute for each value

Example:
php

Copy code

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {

echo $fruit . "<br>"; // Output: Apple, Banana, Cherry

30. What are the different types of operators in PHP? Provide examples of each.

Answer:

Types of Operators:

1. Arithmetic Operators:

o Perform mathematical operations.

o Example: +, -, *, /, %

php

Copy code

$sum = 5 + 3; // 8

2. Assignment Operators:

o Assign values to variables.

o Example: =, +=, -=

php

Copy code

$x = 5; // Assign 5 to $x

$x += 2; // $x is now 7

3. Comparison Operators:

o Compare two values.

o Example: ==, ===, !=, !==, <, >

php

Copy code

if (5 == "5") { // true (type is ignored)

4. Logical Operators:
o Perform logical operations.

o Example: &&, ||, !

php

Copy code

if (true && false) { // false

5. Increment/Decrement Operators:

o Increase or decrease a variable's value by one.

o Example: ++, --

php

Copy code

$a = 5;

$a++; // $a is now 6

31. Explain the difference between == and === operators in PHP.

Answer:

Difference:

1. == (Equality Operator):

o Checks if the values of two operands are equal, ignoring their data types.

o Example:

php

Copy code

if (5 == "5") { // true (type is ignored)

2. === (Identity Operator):

o Checks if the values and data types of two operands are the same.

o Example:

php

Copy code

if (5 === "5") { // false (type is different)

32. What is the purpose of the ternary operator in PHP?


Answer:

Purpose:

 The ternary operator is a shorthand for the if...else statement. It is used for conditional
expressions and simplifies code readability.

Syntax:

php

Copy code

(condition) ? value_if_true : value_if_false;

Example:

php

Copy code

$age = 18

33. How do you declare, initialize and access array elements in PHP?

Answer:

Declaring and Initializing:

 Arrays can be declared using the array() function or the shorthand [].

Example:

php

Copy code

// Indexed Array

$colors = array("Red", "Green", "Blue"); // or $colors = ["Red", "Green", "Blue"];

// Associative Array

$person = array("name" => "John", "age" => 30); // or $person = ["name" => "John", "age" => 30];

Accessing Elements:

 Use the index for indexed arrays or keys for associative arrays.

Example:

php

Copy code

echo $colors[1]; // Output: Green

echo $person["name"]; // Output: John


34. What is the difference between indexed arrays and associative arrays in PHP?

Answer:

Indexed Arrays:

 Arrays where elements are accessed using numerical indexes, starting from 0.

 Example:

php

Copy code

$fruits = array("Apple", "Banana", "Cherry"); // Indexed array

Associative Arrays:

 Arrays where elements are accessed using named keys instead of numerical indexes.

 Example:

php

Copy code

$person = array("name" => "Alice", "age" => 25); // Associative array

Key Differences:

1. Index Type:

o Indexed Arrays: Use integer indices.

o Associative Arrays: Use string keys.

2. Use Cases:

o Indexed Arrays: Suitable for lists where order matters.

o Associative Arrays: Suitable for key-value pairs where relationships are defined.

UNIT:3
35. Discuss various array functions used in PHP.

Answer:
PHP offers a wide range of array functions to manipulate and manage arrays effectively. Here are
some commonly used array functions:

1. array_push():

o Adds one or more elements to the end of an array.

o Example:

php
Copy code

$fruits = array("Apple", "Banana");

array_push($fruits, "Cherry"); // $fruits now contains Apple, Banana, Cherry

2. array_pop():

o Removes the last element from an array and returns it.

o Example:

php

Copy code

$fruit = array_pop($fruits); // $fruit is Cherry, $fruits now contains Apple, Banana

3. array_shift():

o Removes the first element from an array and returns it.

o Example:

php

Copy code

$firstFruit = array_shift($fruits); // $firstFruit is Apple

4. array_unshift():

o Adds one or more elements to the beginning of an array.

o Example:

php

Copy code

array_unshift($fruits, "Mango"); // $fruits now contains Mango, Banana

5. count():

o Counts all elements in an array or something in an object.

o Example:

php

Copy code

$count = count($fruits); // $count is 2

6. sort():

o Sorts an array in ascending order.

o Example:

php
Copy code

sort($fruits); // Sorts the array in alphabetical order

7. array_slice():

o Extracts a portion of an array.

o Example:

php

Copy code

$slicedFruits = array_slice($fruits, 1); // Gets elements from index 1 onward

8. array_merge():

o Merges one or more arrays into one.

o Example:

php

Copy code

$moreFruits = array("Orange", "Grapes");

$allFruits = array_merge($fruits, $moreFruits); // Merges both arrays

36. How do you define and call a function in PHP?

Answer:

Defining a Function:

 Functions in PHP are defined using the function keyword, followed by the function name and
parentheses.

Syntax:

php

Copy code

function functionName($parameter1, $parameter2) {

// Code to execute

return $result; // Optional

Calling a Function:

 To call a function, simply use its name followed by parentheses.

Example:

php
Copy code

function add($a, $b) {

return $a + $b;

// Calling the function

$result = add(5, 3); // $result is 8

37. What are anonymous functions (closures) in PHP, and how are they used?

Answer:

Anonymous Functions:

 Anonymous functions, also known as closures, are functions that do not have a name. They
can be assigned to variables, passed as arguments, or returned from other functions.

Usage:

 They are often used for callbacks and for functional programming techniques.

Example:

php

Copy code

$square = function($n) {

return $n * $n;

};

echo $square(4); // Output: 16

// Using an anonymous function as a callback

$array = [1, 2, 3, 4];

$squaredArray = array_map($square, $array); // Applies the anonymous function

print_r($squaredArray); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )

38. Describe the use of the file_get_contents() function in PHP. How does it differ from fopen() and
fread()?

Answer:

file_get_contents():
 This function reads the entire contents of a file into a string. It is a convenient way to retrieve
file data without opening and reading it manually.

Usage:

php

Copy code

$content = file_get_contents("example.txt");

echo $content;

Differences:

1. fopen():

o Opens a file or URL and returns a file handle.

o Usage: Allows more control over file reading and writing operations.

o Example:

php

Copy code

$handle = fopen("example.txt", "r");

2. fread():

o Reads a specified number of bytes from an open file handle.

o Usage: Requires a file handle to be opened first with fopen().

o Example:

php

Copy code

$handle = fopen("example.txt", "r");

$content = fread($handle, filesize("example.txt"));

fclose($handle);

Comparison:

 file_get_contents() is simpler and faster for reading whole files, while fopen() and fread()
provide more granular control over file operations.

39. Explain how the explode() and implode() functions work in PHP. How are they used to
manipulate strings?

Answer:

explode():

 This function splits a string into an array based on a specified delimiter.


Syntax:

php

Copy code

$array = explode(delimiter, string);

Example:

php

Copy code

$sentence = "Hello World PHP";

$words = explode(" ", $sentence); // $words is ["Hello", "World", "PHP"]

implode():

 This function joins elements of an array into a single string, with a specified delimiter
between each element.

Syntax:

php

Copy code

$string = implode(delimiter, array);

Example:

php

Copy code

$fruits = ["Apple", "Banana", "Cherry"];

$fruitString = implode(", ", $fruits); // $fruitString is "Apple, Banana, Cherry"

40. How do you access the values of radio buttons in a form using PHP? Provide a sample code
snippet.

Answer:

Accessing Radio Button Values:

 Radio buttons in a form are accessed via the $_POST or $_GET superglobal arrays, depending
on the form's method.

Example:

html

Copy code

<form method="post" action="process.php">

<input type="radio" name="gender" value="male"> Male<br>


<input type="radio" name="gender" value="female"> Female<br>

<input type="submit" value="Submit">

</form>

process.php:

php

Copy code

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$gender = $_POST['gender']; // Accessing the radio button value

echo "Selected Gender: " . $gender; // Outputs the selected value

41. What are hidden form fields, and how are they used in PHP? Provide an example of how to
handle hidden fields in a form.

Answer:

Hidden Form Fields:

 Hidden fields are input elements that are not visible to the user but hold data that can be
submitted with the form.

Usage:
 They are useful for storing data that should be sent to the server without user interaction,
like IDs or tokens.

Example:

html

Copy code

<form method="post" action="submit.php">

<input type="hidden" name="user_id" value="12345">

<input type="submit" value="Submit">

</form>

submit.php:

php

Copy code

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$userId = $_POST['user_id']; // Accessing the hidden field value

echo "User ID: " . $userId; // Outputs: User ID: 12345


}

42. How can you combine HTML and PHP code on a single page to process form submissions?
Provide an example that demonstrates form handling and displaying the result on the same page.

Answer:

Combining HTML and PHP:

 You can embed PHP code within HTML to process form submissions and display results on
the same page.

Example:

php

Copy code

<?php

$result = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = htmlspecialchars($_POST['name']); // Get the name input

$result = "Hello, " . $name; // Prepare the output message

?>

<!DOCTYPE html>

<html>

<head>

<title>Form Submission</title>

</head>

<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

Name: <input type="text" name="name" required>

<input type="submit" value="Submit">

</form>

<?php

if (!empty($result)) {
echo "<h2>$result</h2>"; // Display the result if available

?>

</body>

</html>

43. Explain the difference between $_GET and $_POST.

Answer:

$_GET:

 A PHP superglobal array that retrieves data sent to the server via URL query parameters.

 Characteristics:

o Data is visible in the URL.

o Limited data size (maximum URL length).

o Typically used for retrieving data (safe).

Example:

php

Copy code

// URL: script.php?name=John

$name = $_GET['name']; // Accessing the value

$_POST:

 A PHP superglobal array that retrieves data sent to the server via HTTP POST method.

 Characteristics:

o Data is not visible in the URL.

o No size limitations (subject to server configuration).

o Typically used for submitting sensitive data (more secure).

Example:

php

Copy code

// Form submission

$name = $_POST['name']; // Accessing the value

44. Explain various string handling functions in PHP with examples.


Answer:

1. strlen():

o Returns the length of a string.

o Example:

php

Copy code

$str = "Hello";

echo strlen($str); // Output: 5

2. strpos():

o Finds the position of the first occurrence of a substring in a string.

o Example:

php

Copy code

$str = "Hello World";

echo strpos($str, "World"); // Output: 6

3. str_replace():

o Replaces all occurrences of a substring within a string.

o Example:

php

Copy code

$str = "Hello World";

echo str_replace("World", "PHP", $str); // Output: Hello PHP

4. substr():

o Returns a portion of a string.

o Example:

php

Copy code

$str = "Hello World";

echo substr($str, 6, 5); // Output: World

5. trim():

o Removes whitespace from the beginning and end of a string.


o Example:

php

Copy code

$str = " Hello ";

echo trim($str); // Output: Hello

45. Explain various file handling functions in PHP with examples.

Answer:

1. fopen():

o Opens a file or URL and returns a file handle.

o Example:

php

Copy code

$handle = fopen("file.txt", "r"); // Open for reading

2. fread():

o Reads a specified number of bytes from an open file handle.

o Example:

php

Copy code

$content = fread($handle, filesize("file.txt")); // Reads entire file

fclose($handle); // Close the file

3. fwrite():

o Writes data to an open file handle.

o Example:

php

Copy code

$handle = fopen("file.txt", "w"); // Open for writing

fwrite($handle, "Hello World");

fclose($handle);

4. fclose():

o Closes an open file handle.

o Example:
php

Copy code

fclose($handle); // Closes the file

5. file_get_contents():

o Reads the entire file into a string.

o Example:

php

Copy code

$content = file_get_contents("file.txt"); // Reads entire file

46. How can you pass data from an HTML form to a PHP script using the GET method?

Answer:

Using the GET Method:

 Data can be passed to a PHP script via a form using the GET method by including the form
inputs in the URL.

Example:

html

Copy code

<form method="get" action="process.php">

Name: <input type="text" name="name" required>

Age: <input type="number" name="age" required>

<input type="submit" value="Submit">

</form>

process.php:

php

Copy code

if ($_SERVER["REQUEST_METHOD"] == "GET") {

$name = $_GET['name']; // Accessing the form data

$age = $_GET['age'];

echo "Name: " . htmlspecialchars($name) . "<br>";

echo "Age: " . htmlspecialchars($age);

}
UNIT:4
47. How do you set a cookie in PHP? How can you set an expiration date for a cookie?

Answer:

Setting a Cookie:

 Use the setcookie() function to set a cookie in PHP.

Syntax:

php

Copy code

setcookie(name, value, expire, path, domain, secure, httponly);

 Parameters:

o name: Name of the cookie.

o value: Value of the cookie.

o expire: Expiration date in Unix timestamp (optional).

o path: Path on the server where the cookie is available (optional).

o domain: Domain that the cookie is available to (optional).

o secure: Indicates if the cookie should only be transmitted over HTTPS (optional).

o httponly: When set to true, the cookie will only be accessible via the HTTP protocol
(optional).

Example:

php

Copy code

// Setting a cookie with a 1-hour expiration

setcookie("username", "JohnDoe", time() + 3600, "/"); // Expires in 1 hour

48. How can we delete the cookie in PHP?

Answer:

Deleting a Cookie:

 To delete a cookie, set its expiration date to a time in the past using setcookie().

Example:

php

Copy code
// Deleting a cookie

setcookie("username", "", time() - 3600, "/"); // Set to expire in the past

49. How can you check if a cookie exists in PHP? Provide a sample code snippet to demonstrate
this.

Answer:

Checking for a Cookie:

 Use the $_COOKIE superglobal array to check if a cookie exists.

Example:

php

Copy code

if (isset($_COOKIE['username'])) {

echo "Welcome back, " . htmlspecialchars($_COOKIE['username']);

} else {

echo "Hello, guest!";

50. What is the use of query string in PHP? Explain with a proper example.

Answer:

Query String:

 A query string is a part of a URL that contains data to be sent to the server. It typically follows
the ? character and consists of key-value pairs separated by &.

Usage:

 Used to pass data to the server without using form submissions.

Example:

 URL: example.php?name=John&age=30

Accessing Query String Parameters:

php

Copy code

// example.php

$name = $_GET['name']; // John

$age = $_GET['age']; // 30

echo "Name: " . htmlspecialchars($name) . "<br>";

echo "Age: " . htmlspecialchars($age);


51. How can you preserve query string parameters when redirecting a user to another page using
PHP?

Answer:

Preserving Query String Parameters:

 When redirecting, you can append the query string parameters to the URL of the target
page.

Example:

php

Copy code

// Assuming current page has query string parameters

$current_url = $_SERVER['REQUEST_URI']; // Gets the current URL including query string

header("Location: another_page.php" . $current_url); // Redirects with preserved query string

exit();

This ensures that any existing query string parameters are included in the redirection.

You might also like