0% found this document useful (0 votes)
3 views20 pages

WD Practical Study Guide

This study guide covers 11 practical web design topics, including HTML, CSS, JavaScript, and PHP, with detailed code explanations and viva questions. Each practical focuses on specific skills such as creating forms, responsive design, and using Bootstrap. The guide serves as a comprehensive resource for understanding web design fundamentals and preparing for practical assessments.

Uploaded by

sushyask888
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

WD Practical Study Guide

This study guide covers 11 practical web design topics, including HTML, CSS, JavaScript, and PHP, with detailed code explanations and viva questions. Each practical focuses on specific skills such as creating forms, responsive design, and using Bootstrap. The guide serves as a comprehensive resource for understanding web design fundamentals and preparing for practical assessments.

Uploaded by

sushyask888
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Design (WD)

SPPU Practical – Complete Study Guide

All 11 Practicals · Code Explanations · Viva Q&A

# Practical Topic Key Tech

1 Personal Details Page HTML Text Tags

2 Image, Link, Nested Table HTML img/a/table

3 Registration Form HTML Forms

4 CSS Styling (3 types) Internal/External/Inline CSS

5 Responsive Page Bootstrap 5 Grid

6 Form Validation JavaScript, Regex

7 DOM Manipulation JS DOM API

8 Simple Calculator JS Switch-Case

9 PHP Welcome + Date/Time PHP, date()

10 PHP Form with POST PHP $_POST

11 PHP String & Array PHP strlen/strrev/arrays


Practical 1 – HTML Personal Details Page (Text Formatting Tags)

■ What the Code Does


This program creates a basic HTML page that displays personal details of a student using various HTML text
formatting tags like <b>, <strong>, <i>, <em>, and <u>. It also uses headings <h1> and <h2> and paragraph tags <p>.

■ Line-by-Line Explanation
<!DOCTYPE html> Tells the browser this is an HTML5 document.

<html lang='en'> Root element; lang='en' sets language to English for accessibility.

<meta charset='UTF-8'> Supports all characters including special symbols.

<h1><u>My Personal Largest heading, underlined using <u> tag.


Details</u></h1>

<b> vs <strong> <b> = visually bold only. <strong> = bold + semantic importance (used
by screen readers).

<i> vs <em> <i> = visually italic only. <em> = italic + semantic emphasis.

<u> Underlines text. Used for Email label here.

<p> Paragraph tag — wraps each detail on its own line with spacing.

■ Viva Questions & Answers

Q: What is the difference between <b> and <strong>?


A: <b> makes text bold visually (no semantic meaning). <strong> also makes text bold but carries semantic
importance — screen readers will emphasize it. Use <strong> for content that is truly important.

Q: What is the difference between <i> and <em>?


A: <i> makes text italic for stylistic purposes only. <em> makes text italic AND gives it emphasis semantically.
Search engines and screen readers treat <em> as emphasized content.

Q: What does <!DOCTYPE html> do?


A: It is a document type declaration. It tells the web browser that this is an HTML5 document. It must appear as
the very first line before the <html> tag.

Q: What is the purpose of the <head> section?


A: The <head> section contains metadata about the page — title (shown in browser tab), character encoding,
links to CSS/JS files. This content is NOT displayed on the page.

Q: What is charset='UTF-8'?
A: UTF-8 is a character encoding that supports almost all characters from all languages including special symbols,
emojis, and accented letters. It is the standard encoding for web pages.

Q: Name all HTML text formatting tags.


A: <b> Bold, <strong> Important Bold, <i> Italic, <em> Emphasis Italic, <u> Underline, <s> Strikethrough, <sup>
Superscript, <sub> Subscript, <mark> Highlight, <small> Small text, <big> Big text.

Q: What are semantic HTML tags?


A: Semantic tags have meaningful names that describe their content. Examples: <strong>, <em>, <header>,
<footer>, <article>, <nav>. They improve SEO and accessibility.
Q: What is the difference between <h1> to <h6>?
A: <h1> is the largest/most important heading, <h6> is the smallest. Only one <h1> should be used per page
(main title). They create a content hierarchy for SEO and screen readers.
Practical 2 – Image, Hyperlink & Nested Table

■ What the Code Does


This page demonstrates three important HTML features: (1) embedding an image using <img>, (2) creating a clickable
hyperlink using <a> that opens in a new tab, and (3) a nested table — a table inside another table cell — to show
student subject marks.

■ Key Tags Explained


<img src='...' alt='...'> Embeds an image. src = image URL/path. alt = alternative text shown if
image fails to load. No closing tag needed (void element).

<a href='...' target='_blank'> Creates a hyperlink. href = destination URL. target='_blank' opens link
in a NEW tab. Without target, it opens in same tab.

<table border='1' Creates a table. border='1' adds a 1px border. cellpadding adds space
cellpadding='10'> inside each cell.

<tr> Table Row — each horizontal row in the table.

<th> Table Header — bold, centered by default. Used for column headings.

<td> Table Data — regular cell content.

Nested Table A complete <table> placed inside a <td> of the outer table. Used here
to show subjects and marks inside the student row.

■ Viva Questions & Answers

Q: What are the attributes of the <img> tag?


A: src (source path/URL of image), alt (alternate text if image doesn't load — important for accessibility/SEO),
width and height (dimensions), title (tooltip on hover). <img> is a void/self-closing tag — no </img> needed.

Q: What is the difference between target='_blank' and target='_self'?


A: target='_blank' opens the link in a NEW browser tab or window. target='_self' (default) opens the link in the
SAME tab. Other values: _parent (parent frame), _top (full window).

Q: What is a nested table?


A: A nested table is a table placed inside a <td> (table data cell) of another table. It is used when a cell needs to
display structured data itself, like showing multiple subjects with marks inside one student row.

Q: What is cellpadding vs cellspacing?


A: cellpadding = space between cell content and cell border (inside the cell). cellspacing = space between cells
themselves (outside the cell). Both are attributes of the <table> tag.

Q: How do you make a table without borders?


A: Simply remove the border attribute or set border='0'. In CSS, use border: none on table, th, td elements.

Q: What is the alt attribute in <img>?


A: The alt attribute provides alternative text that is displayed when the image cannot be loaded. It is also read by
screen readers for visually impaired users and is important for SEO.

Q: Difference between absolute and relative URL in href?


A: Absolute URL: complete address like [Link] — works from anywhere. Relative URL: path
relative to current file like 'images/[Link]' — used for local files.
Practical 3 – HTML Registration Form

■ What the Code Does


Creates a registration form with fields for Full Name (text), Email (email type), Gender (radio buttons), Date of Birth
(date picker), and a Submit button. The form collects user input using different input types.

■ Form Elements Explained


<form> Container for all form elements. Attributes: method (GET/POST), action
(URL to submit to).

<label for='id'> Clickable label linked to an input by matching 'for' with input's 'id'. Improves
usability.

type='text' Single-line text input for general text like name.

type='email' Like text but validates email format (must contain @). Shows email
keyboard on mobile.

type='radio' Radio button — only ONE can be selected from a group with the SAME
name attribute.

type='date' Shows a date picker calendar. Returns date in YYYY-MM-DD format.

type='submit' Button that submits the form to the server.

required HTML5 attribute — prevents form submission if field is empty. Built-in


validation.

placeholder Ghost text shown inside input before user types. Gives a hint about
expected input.

■ Viva Questions & Answers

Q: What is the difference between GET and POST methods in a form?


A: GET: Data is appended to the URL (visible in browser bar). Limited data, not secure. Used for search forms.
Example: ?name=John&email;=john@[Link]. POST: Data is sent in the request body (not visible in URL). More
secure, no size limit. Used for login, registration, file upload.

Q: What are all HTML5 input types?


A: text, email, password, number, tel, url, date, time, datetime-local, month, week, color, range, file, checkbox,
radio, submit, reset, button, hidden, image, search.

Q: Why do radio buttons have the same 'name' attribute?


A: When multiple radio buttons share the same name, the browser groups them — only ONE can be selected at a
time. If they had different names, multiple could be selected simultaneously.

Q: What is the difference between <input type='submit'> and <button type='submit'>?


A: Both submit the form. <button> can contain HTML content (icons, formatted text) inside it. <input type='submit'>
can only display plain text as its value attribute.

Q: What does the 'required' attribute do?


A: It is an HTML5 validation attribute. If a required field is empty when the user clicks submit, the browser shows a
validation error and prevents form submission automatically — no JavaScript needed.

Q: What is the 'action' attribute in a form?


A: The action attribute specifies the URL/file where the form data will be sent on submission. Example:
action='[Link]'. If omitted, data is sent to the same page.

Q: What is the difference between checkbox and radio button?


A: Checkbox: Multiple options can be selected at once (e.g., hobbies). Each has its own name. Radio button: Only
ONE option can be selected from a group (e.g., gender). All share the same name.
Practical 4 – CSS Styling (Internal, External, Inline)

■ What the Code Does


Demonstrates all three ways to apply CSS: Inline (directly on element), Internal (in <style> tag in <head>), and External
(in a separate .css file). Styles a heading and a student marks table.

■ The Three Types of CSS


Type Where Written Syntax Example Priority

Inline Inside the HTML tag style='color:blue' Highest (3)

Internal In &lt;style&gt; in &lt;head&gt; &lt;style&gt; h1 { color:red; } &lt;/style&gt; Medium (2)

External Separate .css file &lt;link rel='stylesheet' href='[Link]'&gt; Lowest (1)

■ CSS Properties Used


font-family: Arial Sets the font. Arial is a sans-serif font.

background-color Sets background color of an element.

text-align: center Centers text horizontally.

width: 50% Sets table width to 50% of the page.

margin: auto Centers a block element horizontally.

border: 1px solid black Adds a 1 pixel solid black border.

padding: 10px Adds 10px space inside the cell/element.

color: blue Sets text color. Used as inline CSS on h1.

■ Viva Questions & Answers

Q: What is CSS? Why is it used?


A: CSS (Cascading Style Sheets) is used to style and design HTML elements. It controls colors, fonts, layout,
spacing, and animations. It separates content (HTML) from presentation (CSS), making pages easier to maintain
and allowing consistent styling across multiple pages.

Q: What is the priority/specificity order of CSS?


A: Inline CSS > Internal CSS > External CSS. Also: !important overrides all. Specificity: ID selector (#id) > Class
selector (.class) > Element selector (div). The rule is: more specific selectors override less specific ones.

Q: What is the CSS Box Model?


A: Every HTML element is a box with 4 layers: Content (actual text/image), Padding (space inside border), Border
(line around padding), Margin (space outside border). Total width = content width + padding + border + margin.

Q: What is the difference between margin and padding?


A: Padding: space INSIDE the element between content and border (background color shows here). Margin:
space OUTSIDE the element between it and other elements (background color does NOT show here).

Q: How do you link an external CSS file?


A: <link rel='stylesheet' type='text/css' href='[Link]'> — placed inside the <head> section. rel='stylesheet' tells
the browser this is a stylesheet file.

Q: What are CSS selectors? Name types.


A: CSS selectors target HTML elements to apply styles. Types: Element selector (p {}), Class selector
(.classname {}), ID selector (#idname {}), Universal selector (* {}), Descendant selector (div p {}), Pseudo-class
(:hover, :focus), Attribute selector ([type='text']).

Q: What is the 'Cascading' in CSS?


A: Cascading refers to the priority rules that determine which style applies when multiple rules target the same
element. It cascades from: Browser defaults < External < Internal < Inline < !important.
Practical 5 – Responsive Web Page Using Bootstrap

■ What the Code Does


Creates a responsive page using Bootstrap 5. Uses Bootstrap's 12-column grid system to create a 3-column layout,
adds a styled button using Bootstrap component classes. The page automatically adjusts layout for different screen
sizes.

■ Bootstrap Classes Explained


container Centers content with fixed max-width and auto margins on sides.

container-fluid Full-width container stretching the entire viewport width.

text-center Aligns text to center (CSS: text-align: center).

mt-3 / mt-4 Margin top. mt-3 = 1rem, mt-4 = 1.5rem. Bootstrap uses spacing scale 1-5.

row Creates a horizontal row. Must be inside a container. Clears floats.

col-md-4 Column that takes 4/12 = 1/3 width on medium+ screens. Stacks on small screens.

bg-primary Blue background (Bootstrap primary color = #0d6efd).

bg-success Green background.

bg-danger Red background.

text-white White text color.

p-3 Padding of 1rem on all sides.

btn btn-warning Styled button with yellow background.

■ Viva Questions & Answers

Q: What is Bootstrap? Why use it?


A: Bootstrap is a free, open-source CSS framework developed by Twitter. It provides pre-built CSS classes and
JavaScript components for creating responsive, mobile-first websites quickly. Advantages: saves time, ensures
cross-browser compatibility, responsive by default, large community support.

Q: What is the Bootstrap Grid System?


A: Bootstrap uses a 12-column grid layout. Each row is divided into 12 equal columns. You can combine columns:
col-md-6 = half width (6/12), col-md-4 = one-third (4/12), col-md-3 = one-quarter (3/12). Columns must be placed
inside a row, and row inside a container.

Q: What are Bootstrap breakpoints?


A: Bootstrap has 6 breakpoints: xs (<576px), sm (≥576px), md (≥768px), lg (≥992px), xl (≥1200px), xxl (≥1400px).
col-md-4 means 4 columns on medium screens and above — it stacks to full width on smaller screens
automatically.

Q: What is a CDN? How is Bootstrap loaded via CDN?


A: CDN = Content Delivery Network. It serves files from servers closest to the user for fast loading. Bootstrap is
loaded via: <link href='[Link] rel='stylesheet'>

Q: What is responsive web design?


A: Responsive design means a website automatically adapts its layout to fit different screen sizes (desktop, tablet,
mobile) without needing separate mobile sites. Bootstrap achieves this with fluid grid, flexible images, and CSS
media queries.

Q: What is the difference between col-md-4 and col-4?


A: col-4 is always 4 columns wide regardless of screen size. col-md-4 is 4 columns wide only on medium and
larger screens — on small screens it becomes full width (12 columns). Use col-md-X for responsive layouts.
Practical 6 – JavaScript Form Validation

■ What the Code Does


Validates a form using JavaScript before submission. Checks: (1) that name and email fields are not empty, (2) that the
email matches a valid email pattern using Regular Expression (Regex). Shows alerts for errors and success.

■ Code Logic Explained


[Link]('name').value — Gets the text currently typed in the input with id='name'.
if (name == '') — Checks if the field is empty.
var pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/; — Regular expression to validate email format.
[Link](pattern) — Returns match array if email is valid, null if not.
return false — Prevents form from being submitted to server.
return true — Allows form submission to proceed.

■ Regex Pattern Breakdown: /^[^ ]+@[^ ]+\.[a-z]{2,3}$/


Part Meaning

^ Start of string

[^ ]+ One or more characters that are NOT a space (username part)

@ Must contain literal @ symbol

[^ ]+ One or more non-space characters (domain name)

\. Literal dot (. escaped)

[a-z]{2,3} 2 to 3 lowercase letters (e.g., com, in, org)

$ End of string

■ Viva Questions & Answers

Q: What is JavaScript form validation?


A: Form validation using JavaScript checks user input on the client-side (in browser) before sending data to the
server. This saves time, reduces server load, and gives instant feedback to users. It validates required fields,
email formats, password strength, number ranges, etc.

Q: What is the difference between client-side and server-side validation?


A: Client-side: runs in browser using JavaScript — fast, immediate feedback, but can be bypassed by disabling
JS. Server-side: runs on server using PHP/Python — secure, cannot be bypassed, but requires a round-trip to
server. BOTH should be used for security.

Q: What is a Regular Expression (Regex)?


A: A regular expression is a pattern used to match/search strings. In JavaScript, patterns are enclosed in
/pattern/flags. Used for validating email, phone numbers, passwords. Common methods: [Link](regex),
[Link](string).

Q: What does return false do in a form's onsubmit?


A: When the function called by onsubmit returns false, the browser cancels the form submission — data is NOT
sent to the server. When it returns true, the form submits normally.

Q: How do you get the value from an input field in JavaScript?


A: Using [Link]('inputId').value — this returns the current text in the input as a string. For
numbers, wrap with parseInt() or parseFloat().
Q: What is the alert() function?
A: alert() displays a popup dialog box with a message and an OK button. It is used to show errors or notifications
to users. Other dialog functions: confirm() (OK/Cancel), prompt() (input dialog).

Q: What are other ways to select elements in JavaScript?


A: [Link]('id') — by ID (returns single element). [Link]('class')
— by class (returns HTMLCollection). [Link]('tag') — by tag.
[Link]('#id') — CSS selector, first match. [Link]('.class') — CSS selector,
all matches.
Practical 7 – JavaScript DOM Manipulation

■ What the Code Does


Demonstrates DOM (Document Object Model) manipulation. When the user clicks a button, a JavaScript function
accesses a <p> element by its ID and changes its text content dynamically without reloading the page.

■ Code Logic Explained


DOM = Document Object Model. The browser creates a tree of all HTML elements when it loads a page. JavaScript
can access and modify this tree to change content, styles, and structure dynamically.

[Link]('output') — Finds the element with id='output' in the DOM tree.


.innerHTML — Property that gets or sets the HTML content inside an element. Setting it changes what is displayed on
the page instantly.
onclick='showMessage()' — Event attribute that calls showMessage() when button is clicked.

■ Viva Questions & Answers

Q: What is the DOM?


A: DOM (Document Object Model) is a programming interface for HTML documents. When a browser loads an
HTML page, it creates a tree-like structure of objects representing all elements. JavaScript can use the DOM to
dynamically read, change, add, or remove HTML elements and attributes.

Q: What is the difference between innerHTML and innerText?


A: innerHTML: Gets/sets the HTML content including tags. Example: [Link] = '<b>Hello</b>'
renders bold text. innerText: Gets/sets only the plain text, strips HTML tags. Example: [Link] =
'<b>Hello</b>' shows literal tags as text.

Q: What is an event in JavaScript?


A: An event is an action that occurs in the browser — user clicking, hovering, typing, page loading, etc. JavaScript
can 'listen' for events and run code in response. Common events: onclick, onmouseover, onkeydown, onsubmit,
onload, onchange.

Q: What is addEventListener()? How is it different from onclick?


A: addEventListener('click', function) attaches an event handler to an element. Advantage: multiple handlers can
be added to the same event on same element. onclick attribute only allows one handler. addEventListener is the
modern, preferred approach.

Q: What are the ways to change element content in JS?


A: innerHTML (sets HTML), innerText (sets plain text), textContent (similar to innerText but includes hidden
elements). To change style: [Link] = 'red'. To change attribute: [Link]('src','[Link]').

Q: What is [Link]()? Give example.


A: Creates a new HTML element dynamically. Example: var p = [Link]('p'); [Link] =
'New paragraph'; [Link](p); — This creates and adds a new <p> to the page.
Practical 8 – JavaScript Calculator (switch-case)

■ What the Code Does


A simple calculator that takes two numbers and an operator from the user, performs the selected arithmetic operation
using a switch-case statement, and displays the result on the page.

■ Code Logic Explained


parseFloat() — Converts the string value from the input field into a decimal number. Without this, JavaScript would
concatenate strings instead of adding numbers.

switch(op) — Evaluates the operator variable. Each case matches a possible operator (+, -, *, /).
break — Exits the switch after a matching case. Without break, execution 'falls through' to next case.
default — Runs if no case matches (like else in if-else).
[Link]('result').innerHTML — Displays the result on the page.

■ Viva Questions & Answers

Q: What is a switch-case statement? When to use it over if-else?


A: switch-case checks one variable against multiple possible values. Use it when checking a single variable
against many specific values (like operators, day names, menu choices). if-else is better for complex conditions
with ranges (if x > 10 && x < 20). switch is generally more readable for multiple fixed value comparisons.

Q: What happens if we forget the 'break' statement in switch?


A: Fall-through occurs — after matching a case, execution continues into the NEXT case even without a match.
Example: if case '+' has no break, after addition it also executes case '-' code. Always add break unless
fall-through is intentional.

Q: What is the difference between parseInt() and parseFloat()?


A: parseInt('3.7') returns 3 — converts to whole integer, drops decimal part. parseFloat('3.7') returns 3.7 —
converts to floating point, keeps decimals. For a calculator, parseFloat is better to handle decimal numbers.

Q: What happens when you divide by zero in this calculator?


A: In JavaScript, dividing by zero gives Infinity (not an error like in other languages). 0/0 gives NaN (Not a
Number). The calculator doesn't handle this case — in an improved version, you should add: if(op == '/' && num2
== 0) { alert('Cannot divide by zero'); return; }

Q: What is NaN in JavaScript?


A: NaN stands for 'Not a Number'. It results from invalid math operations like 0/0, parseInt('abc'), or [Link](-1).
You can check for NaN using isNaN(value) — direct comparison like value === NaN always returns false.

Q: What is the difference between == and === in JavaScript?


A: == (loose equality): compares values after type conversion. '5' == 5 is TRUE. === (strict equality): compares
both value AND type. '5' === 5 is FALSE. Always use === to avoid unexpected type coercion bugs.
Practical 9 – PHP Welcome Page with Date & Time

■ What the Code Does


A PHP script that displays a Welcome heading and the current date and time on the server. Sets the timezone to
Asia/Kolkata (IST) so the time shown is Indian Standard Time.

■ Code Logic Explained


<?php ... ?> — PHP code block. Everything inside is executed on the server.
date_default_timezone_set('Asia/Kolkata') — Sets timezone to IST (+5:30). Must be called before date().
echo — PHP's print statement. Outputs text/HTML to the browser.
date('d-m-Y') — Returns current date. d=day(01-31), m=month(01-12), Y=4-digit year.
date('h:i:s A') — Returns current time. h=12-hour, i=minutes, s=seconds, A=AM/PM.

■ PHP date() Format Characters


Character Meaning Example

d Day with leading zero 05

D Day abbreviation Mon

m Month with leading zero 06

M Month abbreviation Jun

Y 4-digit year 2025

y 2-digit year 25

H 24-hour format 14

h 12-hour format 02

i Minutes 30

s Seconds 45

A AM/PM PM

l Full day name Monday

■ Viva Questions & Answers

Q: What is PHP?
A: PHP (Hypertext Preprocessor) is a server-side scripting language used for web development. PHP code runs
on the WEB SERVER, generates HTML output, and sends it to the browser. The browser only sees HTML — it
never sees the PHP source code. PHP files have .php extension.

Q: What is the difference between server-side and client-side languages?


A: Client-side (HTML, CSS, JavaScript): runs in the user's browser. Server-side (PHP, Python, [Link]): runs on
the web server before sending to browser. PHP can connect to databases, access files, handle sessions — things
JavaScript in the browser cannot do.

Q: What is echo in PHP?


A: echo is PHP's output statement. It outputs text or HTML to the browser. Example: echo 'Hello World'; — Also:
echo '<h1>' . $var . '</h1>'; The dot (.) is PHP's string concatenation operator. print is similar but slightly slower.

Q: What does date_default_timezone_set() do?


A: It sets the default timezone for all date/time functions in the script. Without it, PHP uses the server's default
timezone which may not be IST. Must be called BEFORE using the date() function.
Q: What is the difference between echo and print in PHP?
A: echo: faster, can output multiple values (echo 'a','b'). No return value. print: slightly slower, can only output one
value, returns 1 (so can be used in expressions). In practice, echo is almost always preferred.

Q: What is a PHP variable? How is it different from JavaScript?


A: PHP variables start with $ sign: $name = 'John'; PHP is loosely typed — no need to declare type. Difference
from JS: PHP variables are prefixed with $, PHP runs on server not browser, PHP strings use . for concatenation
while JS uses +.
Practical 10 – PHP Form with POST Method

■ What the Code Does


A PHP page that shows a form (HTML) and also processes the submitted data (PHP). When the form is submitted
using POST method, PHP retrieves the values and displays them. The same file handles both showing and processing
the form.

■ Code Logic Explained


$_POST — PHP superglobal array. Contains all data sent via POST method. $_POST['name'] gets the value of the
input with name='name'.

$_SERVER['REQUEST_METHOD'] — Returns the HTTP method used ('GET' or 'POST'). Used to check if the form
was submitted before trying to access $_POST values.

$name = $_POST['name'] — Retrieves posted value and stores in PHP variable.

echo 'Name: ' . $name — Concatenates and outputs the retrieved value.

■ Viva Questions & Answers

Q: What are PHP superglobals?


A: Superglobals are built-in PHP variables that are always available in all scopes. Main superglobals: $_GET
(query string data), $_POST (form POST data), $_REQUEST (GET+POST+COOKIE), $_SESSION (session
data), $_COOKIE (cookie data), $_SERVER (server/environment info), $_FILES (uploaded file data), $GLOBALS
(all global variables).

Q: What is the difference between $_GET and $_POST?


A: $_GET: Data from URL query string (?name=John). Visible in URL, max ~2000 chars, bookmarkable, not for
sensitive data. $_POST: Data from form body. Hidden from URL, no size limit (default 8MB), more secure for
passwords/sensitive info.

Q: Why do we check $_SERVER['REQUEST_METHOD'] == 'POST'?


A: When the page first loads (no submission), there is no POST data — accessing $_POST['name'] directly would
cause an 'Undefined index' warning. The check ensures PHP only tries to read form data when the form was
actually submitted via POST.

Q: What is string concatenation in PHP?


A: In PHP, strings are joined using the dot (.) operator. Example: $greeting = 'Hello ' . $name; This is different from
JavaScript which uses + for concatenation. .= is the concatenation assignment operator: $str .= ' more text';

Q: How do you prevent XSS (Cross-Site Scripting) in PHP forms?


A: Use htmlspecialchars() to sanitize output: echo htmlspecialchars($name); This converts <, >, &, ' to HTML
entities, preventing malicious scripts from being injected. Also use strip_tags() to remove all HTML tags from
input.

Q: What is the difference between a PHP variable and a constant?


A: Variable: $name = 'John'; can be changed. Constant: define('PI', 3.14); cannot be changed. Constants don't
use $ prefix, are global by default, and by convention are UPPERCASE.
Practical 11 – PHP String Manipulation & Arrays

■ Practical 11a – String Manipulation


Accepts a string from a form and performs three operations: finds its length (strlen), reverses it (strrev), and extracts
the first 5 characters (substr).

■ PHP String Functions


Function What It Does Example

strlen($str) Returns number of characters in string strlen('Hello') = 5

strrev($str) Returns the string reversed strrev('Hello') = 'olleH'

substr($str, start, len) Returns substring. start=0 means from beginning substr('Hello', 0, 3) = 'Hel'

strtoupper($str) Converts string to UPPERCASE strtoupper('hello') = 'HELLO'

strtolower($str) Converts string to lowercase strtolower('HELLO') = 'hello'

str_replace(find, replace, str) Replaces occurrences of find with replace str_replace('o','0','Hello') = 'Hell0'

trim($str) Removes whitespace from both ends trim(' hi ') = 'hi'

strpos($str, find) Returns position of first occurrence (0-indexed) strpos('Hello','l') = 2

str_repeat($str, n) Repeats string n times str_repeat('Hi',3) = 'HiHiHi'

■ Practical 11b – PHP Arrays


Accepts 3 names via a form using an array input (name[]). PHP collects them as an array in $_POST['name'] and
iterates with foreach to display each name.

■ PHP Array Concepts


name[] in HTML form — Using [] in the input name attribute tells PHP to collect multiple inputs with the same name
into an array automatically.

$names = $_POST['name'] — $names becomes an indexed array: $names[0], $names[1], $names[2].

foreach ($names as $n) — Loops through each element of the array. $n holds the current element's value.

PHP Array Types: Indexed arrays ($arr = ['a','b','c']), Associative arrays ($arr = ['name'=>'John', 'age'=>21]),
Multidimensional arrays (arrays inside arrays).

■ PHP Array Functions


Function What It Does

count($arr) Returns number of elements

array_push($arr, val) Adds element to end

array_pop($arr) Removes and returns last element

sort($arr) Sorts array in ascending order

array_reverse($arr) Returns reversed array

in_array(val, $arr) Returns true if value exists in array

array_merge($a, $b) Merges two arrays

implode(', ', $arr) Joins array elements into a string


explode(',', $str) Splits a string into an array

■ Viva Questions & Answers

Q: What is substr() in PHP? What are its parameters?


A: substr(string, start, length) — extracts a portion of a string. string = the original string. start = starting position (0
= first character). length = how many characters to extract (optional — if omitted, goes to end of string). Negative
start counts from end: substr('Hello', -3) = 'llo'.

Q: What is the difference between strlen and mb_strlen?


A: strlen() counts bytes, not characters — gives wrong results for multibyte characters (UTF-8 Hindi/Chinese).
mb_strlen() correctly counts the number of actual characters in multibyte strings. For English text, both give the
same result.

Q: What is a foreach loop in PHP?


A: foreach is used specifically for iterating over arrays. Syntax: foreach ($array as $value) { } or foreach ($array as
$key => $value) { } for associative arrays. It automatically handles the iteration — no need to manage an index
counter.

Q: What is the difference between indexed and associative arrays in PHP?


A: Indexed: uses numeric keys automatically (0,1,2...). $arr = ['Apple','Banana','Cherry']; Access: $arr[0].
Associative: uses named string keys. $arr = ['name'=>'John', 'age'=>21]; Access: $arr['name']. Both can hold
mixed data types.

Q: How does PHP handle name[] in HTML form?


A: When multiple input fields have name='name[]', PHP automatically collects their values into an indexed array.
$_POST['name'] becomes an array: ['John', 'Jane', 'Bob']. Without [], only the last value would be stored.

Q: What is strpos() and how is it different from strstr()?


A: strpos($str, $find) returns the numeric POSITION (index) of first occurrence, or false if not found. strstr($str,
$find) returns the portion of the string FROM the first occurrence to end. Example: strpos('Hello World', 'World') =
6. strstr('Hello World', 'World') = 'World'.
■ Quick Revision Cheat Sheet
Topic Key Points to Remember

HTML Tags &lt;b&gt; bold, &lt;i&gt; italic, &lt;u&gt; underline, &lt;strong&gt; important bold, &lt;em&gt; emphasis italic

img tag src=path, alt=alternative text, void element (no closing tag)

a tag href=URL, target='_blank' opens new tab

Tables &lt;table&gt;, &lt;tr&gt;=row, &lt;th&gt;=header, &lt;td&gt;=data, cellpadding=inner space

Forms &lt;form method='POST' action='[Link]'&gt;, input types: text/email/radio/date/submit

CSS Types Inline &gt; Internal &gt; External (priority). Inline: style=''. Internal: &lt;style&gt;. External: &lt;link&gt;

CSS Box Model Content → Padding → Border → Margin

Bootstrap Grid 12 columns total. container &gt; row &gt; col-md-X. col-md-4 = 1/3 width

JS Validation [Link]('id').value, email regex /^[^ ]+@[^ ]+\.[a-z]{2,3}$/, return false stops submit

JS DOM innerHTML sets HTML content, innerText sets plain text, onclick handles click events

JS Calculator parseFloat() converts string to number, switch-case for operations, break prevents fall-through

PHP Basics PHP runs on server, &lt;?php ?&gt; tags, echo to output, $ prefix for variables, . for concatenation

PHP date() date_default_timezone_set('Asia/Kolkata'), date('d-m-Y'), date('h:i:s A')

PHP Forms $_POST['fieldname'], check $_SERVER['REQUEST_METHOD']=='POST' first

PHP Strings strlen(), strrev(), substr(str,start,len), strtoupper(), strtolower(), str_replace()

PHP Arrays name[] in HTML = array in PHP, foreach loop, count(), sort(), in_array()

All the best for your WD Practical! You've got this! ■

You might also like