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

PHP Sy Bca

This document provides a question bank on PHP programming concepts with questions and explanations. It covers PHP tags, running PHP in HTML files, why PHP is a scripting language, creating links, the foreach loop, include vs require, GET vs POST methods, server-side scripting, variable scopes, the substring function, array types, string functions like strlen and strpos, the $_REQUEST variable, echo vs print, superglobal variables, literals, and the ternary operator.

Uploaded by

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

PHP Sy Bca

This document provides a question bank on PHP programming concepts with questions and explanations. It covers PHP tags, running PHP in HTML files, why PHP is a scripting language, creating links, the foreach loop, include vs require, GET vs POST methods, server-side scripting, variable scopes, the substring function, array types, string functions like strlen and strpos, the $_REQUEST variable, echo vs print, superglobal variables, literals, and the ternary operator.

Uploaded by

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

PHP Programming

Question Bank
a) What these tags specify in PHP : <?php and ?> ->
PHP, the tags <?php and ?> are called opening and closing tags. These tags
tell PHP to start and stop interpreting the code between them.
The code between these tags is considered PHP code. It will be executed
on the server side before the requested file is sent to the client browser
b) Can we run PHP from HTML file? If yes, how?
-> Yes, you can embed PHP code within an HTML file, and the server will process it before
sending the response to the client. To achieve this, follow these steps:Ensure that your
server supports PHP. Most web servers, like Apache or Nginx, have PHP support.Save your
HTML file with a .php extension, for example, index.php.Write your HTML content along
with PHP code enclosed in <?php and ?> tags. Here's a simple example:<!DOCTYPE html>
<html>
<head>
<title>PHP in HTML</title>
</head>
<body>
<?php
// PHP code here echo
"Hello, this is PHP!";
?>
</body>
</html>

c)Why PHP is known as scripting language?


-> PHP is considered a scripting language because it is primarily designed for scripting
purposes, particularly for web development.
PHP is not compiled into machine code before execution. Instead, it is interpreted at
runtime.
The PHP interpreter reads and executes the code line by line, making it easy to modify and
test scripts without the need for a separate compilation step.
PHP is particularly popular for server-side scripting in web development.
It is embedded within HTML code and executed on the server to generate dynamic web
pages.
This scripting capability is essential for creating interactive and data-driven websites.

e) How can we create links in PHP pages?


->In PHP, you can create links in a manner similar to HTML. You can use the anchor (<a>) tag to
create hyperlinks.
f) What is the function of “foreach” construct in PHP?
->The foreach construct in PHP is used to iterate over arrays or other iterable objects, such as
strings or objects implementing the Traversable interface.
It simplifies the process of looping through each element in an array without needing to manually
manage the iteration process.
The basic syntax of foreach is as follows: foreach
(array_expression as $value) {
// code to be executed for each iteration using $value
}
Here's a simple example of using foreach with an array:$fruits = array("apple", "banana", "orange",
"grape");

foreach ($fruits as $fruit)


{ echo $fruit . "<br>";
}
i) What is the difference between include and require?
->include() require()
The include() function does not stop the execution of the script even
if any error occurs.

The require() function will stop the execution of the script when
an error occurs.

The include() function does not give a fatal error.

The require() function gives a fatal error

The include() function is mostly used when the file is not required
and the application should continue to execute its process when
the file is not found.

The require() function is mostly used when the file is mandatory


for the application.

The include() function will only produce a warning


(E_WARNING) and the script will continue to execute.

The require() will produce a fatal error (E_COMPILE_ERROR) along


with the warning and the script will stop its execution.

The include() function generate various functions and elements that


are reused across many pages taking a longer time for the process
completion.
The require() function is more in recommendation and considered
better whenever we need to stop the execution incase of
availability of file, it also saves time avoiding unnecessary
inclusions and generations.

j) Differences between GET and POST methods?


->GET POST
1) In case of Get request, only limited amount of data can be sent because data is sent in header.

In case of post request, large amount of data can be sent because data is sent in body.

2) Get request is not secured because data is exposed in URL bar.

Post request is secured because data is not exposed in URL bar.

3) Get request can be bookmarked.

Post request cannot be bookmarked.

4) Get request is idempotent . It means second request will be ignored until response of first
request is delivered

Post request is non-idempotent.

5) Get request is more efficient and used more than Post.

Post request is less efficient and used less than get.

k) What do you mean by Server Side Scripting?


-> Server-side scripting refers to the execution of scripts on a web server, where the processing
takes place on the server rather than the client's browser.
In this model, the server generates dynamic web pages in response to client requests by executing
server-side scripts.
These scripts are typically written in server-side programming languages, such as PHP, Python,
Ruby, Java, or Node.js.
Common use cases for server-side scripting include form handling, authentication, data processing,
content management systems (CMS), and other server-intensive tasks

l) Explain all possible types of scope of variable?


-> In programming, variable scope refers to the region of the program where a variable is accessible
or visible.
In many programming languages, including PHP, JavaScript, and others, variables can have different
scopes.
The three main types of variable scope are:
Global Scope:A variable declared in the global scope is accessible throughout the entire program. It
is defined outside of any function or block and can be used both inside and outside functions. Local
Scope:A variable declared within a function or a block is said to have local scope. It is only
accessible within that specific function or block and is not visible outside of it.
Static Scope (Static Variables):In some languages like PHP, variables can have static scope within a
function.
A static variable retains its value between multiple calls to the same function.

m) Explain with example the use of substring function?


o) What do you understand about Numeric array, Associative array and Multidimensional array?
->Numeric Array: A numeric array is a collection of elements where each element is accessed by an
index or a numeric key. Elements are indexed numerically, starting from 0.Indexed access is based
on numerical keys.
Example (in PHP):$numericArray = array("Apple", "Banana", "Orange");
echo $numericArray[1]; // Output: Banana Associative
Array:
An associative array is a collection of elements where each element is associated with a specific key
instead of numerical indices.
Elements are accessed using named keys.
Key-value pairs are used to store and retrieve data.
Example (in PHP):
$associativeArray = array("fruit1" => "Apple", "fruit2" => "Banana", "fruit3" => "Orange"); echo
$associativeArray["fruit2"]; // Output: Banana

Multidimensional Array:
A multidimensional array is an array of arrays, where each element can be an array itself.
Used to represent tables, matrices, or data structures with multiple dimensions.
Elements can be accessed using multiple indices. Example (in PHP):
$multidimensionalArray = array( array("Apple", "Banana", "Orange"),
array("Red", "Yellow", "Orange")
);
echo $multidimensionalArray[0][1]; // Output: Banana

p) What is the use of strlen() and strpos() functions?


->The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string
as a parameter and returns its length
<?php
$str = "GeeksforGeeks"; echo
strlen($str);
?> strpos() Function: This function helps us to find the position of the first occurrence of a
string in another string. This returns an integer value of the position of the first occurrence of
the string. This function is case-sensitive, which means that it treats upper-case and lower-case
characters differently.

q) Why we use $_REQUEST variable? Write a note on various library


functions available in PHP? ->The $_REQUEST variable in PHP is a
superglobal array that is used to collect data from HTML forms or to
include data passed in the URL. It merges the contents of $_GET, $_POST,
and $_COOKIE arrays into one associative array, providing a convenient
way to access data from various sources without having to explicitly
specify the source.

w) Explain the following:


1) Echo vs Print
->1.echo accepts a list of arguments (multiple arguments can be passed), separated by commas.
print accepts only one argument at a time.
2.
It returns no value or returns void.
It returns the value 1.
3.
It displays the outputs of one or more strings separated by commas.
The print outputs only the strings.
4.
It is comparatively faster than the print statement.
It is slower than an echo statement

2) Super global variable


->In PHP, superglobals are special predefined variables that are always accessible, regardless of
scope, and they contain various information related to the server, request, and environment.
These variables are referred to as "superglobals" because they are automatically global and can be
used anywhere in your PHP scripts.
Here are some commonly used superglobal variables in PHP:
$_GET:Contains data sent to the script via URL parameters using the HTTP GET method.
Example:
$username = $_GET['username'];

$_POST:Contains data sent to the script via HTTP POST method, typically from a form.
Example:
$password = $_POST['password']!;

$_REQUEST:Contains data from both $_GET and $_POST. It's a merged array of input data, but be
cautious about security implications.
// Example:
$inputData = $_REQUEST['input_data'];

3) Literals
->a literal refers to the representation of a fixed value directly within the source code of a program.
It is a way to express values in a human-readable format.
4) Ternary operator
-> The ternary operator, also known as the conditional operator, is a concise way to write a simple
if-else statement in PHP. It has the following syntax: condition ? expression_if_true :
expression_if_false;
It provides a more concise way to express simple conditions.It returns the result of the
expression_if_true if the condition is true; otherwise, it returns the result of expression_if_false.It's
often used for quick assignments or inline conditions.
It can be nested for more complex scenarios, but readability should be considered.

5) Break and continue


-> break:The break statement is used to exit a loop prematurely, terminating the execution of the
loop's block of code.

continue:The continue statement is used to skip the rest of the code inside a loop for the current
iteration and move to the next iteration.

1.Write difference between GET and POST method.


2. Explain different types of arguments passing to functions with example.
->In PHP, there are mainly two types of arguments passing to functions: pass by value and pass
by reference.
Pass by Value: In pass by value, a copy of the variable's value is passed to the function. Any
changes made to the parameter inside the function do not affect the original variable outside
the function. This is the default behavior in PHP.
Example: function increment($num) {
$num++; echo "Inside function:
$num <br>";
}
$number = 5; increment($number);
echo "Outside function: $number";
Output: Inside function: 6
Outside function: 5
Pass by Reference: In pass by reference, a reference to the variable is passed to the function.
Any changes made to the parameter inside the function affect the original variable outside the
function.
To pass an argument by reference, use the & symbol before the parameter name in both the
function declaration and the function call.
Example: function incrementByReference(&$num) {
$num++; echo "Inside function:
$num <br>";
}
$number = 5;
incrementByReference($number); echo
"Outside function: $number";
Output: Inside function: 6
Outside function: 6
3. What is the difference between function overloading and overriding? Explain.
->Function Overloading
Function Overriding

Function Overloading provides multiple definitions of the function by changing signature.


Function Overriding is the redefinition of base class function in its derived class with same
signature.

An example of compile time polymorphism.


An example of run time polymorphism.

Function signatures should be different.


Function signatures should be the same.

Overloaded functions are in same scope.


Overridden functions are in different scopes.

Overloading is used when the same function has to behave differently depending upon
parameters passed to them.
Overriding is needed when derived class function has to do some different job than the base
class function.

A function has the ability to load multiple times.


A function can be overridden only a single time.

In function overloading, we don’t need inheritance.


In function overriding, we need an inheritance concept.
4. What is the difference between the include() and require() functions?
5. Define Introspection and explain it with suitable example.
->Introspection is the ability of a program to examine an object’s characteristics, such as its
name, parent class (if any), properties, and methods.
With introspection, you can write code that operates on any class or object.
You don’t need to know which methods or properties are defined when you write your
code;instead, you can discover that information at runtime, which makes it possible for you to
write generic debuggers, serializers, profilers, etc
Introspection is particularly useful for tasks like debugging, dynamically interacting with
objects, or implementing flexible, generic functions that can operate on different types of
objects.

6. Differentiate between implode and explode functions.


->implode():implode() is used to join array elements with a string.It takes two parameters: the
glue (string) which is used to join the elements, and the array of elements.It returns a string
containing all the array elements joined by the specified glue string.
Example:$array = array('Hello', 'World', '!');
$string = implode(' ', $array); echo $string; //
Output: Hello World !explode():

explode() is used to split a string into an array of substrings based on a delimiter.It takes three
parameters: the delimiter (string) on which to split the input string, the input string, and
optionally, the limit (integer) which specifies the maximum number of elements to return.It
returns an array containing the substrings.
Example:$string = "apple,banana,orange";
$array = explode(',', $string); print_r($array); // Output: Array ( [0] => apple
[1] => banana [2] => orange )
7. Explain Inserting and Retrieving the query result operations.
->
8. Explain web page validation with example.
->Validation in PHP is the process where we check if the input information in the various fields
in any form such as text, checkbox or radio button, etc, submitted by the end-user in the form
is correct or not using HTML code.
There are 2 kinds of validation available in PHP:
Client-Side Validation: This type of validation is done on the web browser of the client machine.
Server-Side Validation: The data on submission is then sent to the server machine to perform
validation checks there.
9. Explain the following string functions with example.
i) str_replace()
->Example
Replace the text "World" with "Dolly":
$x = "Hello World!";
echo str_replace("World", "Dolly", $x);
The str_replace() function is used to replace occurrences of a search string with a re
ii) ucwords()
-> $str = "the quick brown fox"; $new_str = ucwords($str); echo $new_str;Output:The
Quick Brown Fox the ucwords() function is used to convert the first character of each
word in a string to uppercase.
iii) strlen()
->The PHP strlen() function returns the length of a string.
• Example
• Return the length of the string "Hello world!": echo strlen("Hello
world!"); iv) strtoupper()
->$str = "hello world";
$new_str = strtoupper($str); echo $new_str;Output:HELLO WORLD the
strtoupper() function is used to convert all characters in a string to uppercase.

11. Define the use of foreach loop in php with example.


-> The foreach loop is used to traverse the array elements. It works only on array and object. It
will issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to
iterate the elements of an array.
In foreach loop, we don't need to increment the value.
<?php
$fruits = array("apple", "banana", "orange");

foreach ($fruits as $fruit)


{ echo $fruit . "<br>";
}
?> o/p:-
apple
banana
orange
12. What is a Regular Expression? Explain with example.
->Regular expressions are commonly known as regex.
These are nothing more than a pattern or a sequence of characters, which describe a special
search pattern as text string.
Regular expression allows you to search a specific string inside another string.
Even we can replace one string by another string and also split a string into multiple chunks.
They use arithmetic operators (+, -, ^) to create complex expressions. By
default, regular expressions are case sensitive.
Example:-
To check email is valid or not
/^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$/

13. List out the advantages of PHP.


->The most important advantage of PHP is that it’s open-source and free from cost.
It can be downloaded anywhere and is readily available to use for events or web applications.
It is platform-independent. PHP-based applications can run on any OS like UNIX, Linux,
Windows, etc.
Applications can easily be loaded which are based on PHP and connected to the database.
It’s mainly used due to its faster rate of loading over slow internet speed than other
programming language.
It helps in managing code easily.

14. Explain control statements with syntax and example in PHP.


-> Control statements in PHP are conditional statements that execute a block of statements if
the condition is correct. The statement inside the conditional block will not execute until the
condition is satisfied.
There are two types of control statements in PHP:
Conditional statements are used to execute code based on a condition.
Loop statements are used to repeat a block of code a certain number of times.

Conditional Statements:
if statement: if
(condition) {
// code to execute if condition is true
}Example:$age = 20; if
($age >= 18) {
echo "You are an adult.";
}
if-else statement: if
(condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}Example:$age = 15; if
($age >= 18) {
echo "You are an adult.";
} else { echo "You are a
minor.";
}
else if statement (also known as elseif): if
(condition1) {
// code to execute if condition1 is true }
elseif (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if all conditions are false
}Example:$grade = 75;
if ($grade >= 90)
{ echo "A";
} elseif ($grade >= 80)
{ echo "B";
} elseif ($grade >= 70) {
echo "C"; } else
{ echo "F";
}
Loop Statements: for
loop:
for (initialization; condition; increment/decrement) {
// code to be executed }Example:for
($i = 0; $i < 5; $i++) { echo $i;
}
while loop:
while (condition) {
// code to be executed
}Example:$i = 0; while ($i
< 5) { echo $i;
$i++;
}
do-while loop:
do {
// code to be executed } while
(condition);Example:$i = 0; do
{ echo $i;
$i++;
} while ($i < 5);
15. Write the PHP code for fetching the data from a database to a webpage?
-> create table student (rollno int primary key, name varchar(20), City (20) char, age int (10)); <?
php

$server = "localhost";
$user = "root";
$password=" ";
$database = "get";
$conn = new mysqli ($server, $user, $password, $database);
if ($conn ->connect_error) { die ("connection failed:" .
$conn-> connect_eror);
}
$query = "SELECT * FROM student";
$result = $conn->query($query); if
($result->num_rows >0) { while
($row = $result ->fetch_row())
{
echo "Roll No". $row ["rollno "]. " - Name:". $row ["Name"]." | City:", $row["City"]. " | Age:".
$row["Age"]."<br>";
}
}
else{
echo "0 results";
}
$conn-> close();
?>
16. Explain anonymous function concept in PHP.
-> Anonymous function is a function without any user defined name.
Such a function is also called closure or lambda function.
Sometimes, you may want a function for one fime use.
Closure is an anonymous function which closes over the environment in which it is defined.
Most common use of anonymous function to create an inline callback function.
Example:-
<?php
$var = function ($x)
{ return pow($x,3);
}
echo "cube of 3 = ". $var (3);
?> Syntax:
$var = function ($arg1, $arg2 )
{ return $val; };

17. Explain any four string functions with example.


18. Write a php function to find area of circle and rectangle.
19. Explain any five string related functions with example.
20. Write a PHP script which takes the username, password and e-mail values from user and
checks whether the user has filled the textboxes or not. Also, check the e-mail field
whether it is incorrect format or not.
21. Explain the execution of php script using diagram.
22. Differentiate between static web sites and dynamic web sites.
-> Static Website
1) Content of web pages can not be change at runtime.
2) No interaction with database possible.
3.) It is faster to load as compared to dynamic website. 4)
Cheaper Development costs.
5) No feature of content management.
6) HTML, CSS, Javascript is used for developing the website.

Dynamic Website.
1.) Content of Web pages can be changed. 2)
Interaction with database is possible.
3.) It is slower than static website. 4)
More Development cost.
5)Feature of content management system.
6.) server side languages such as PHP, Node.js are used.

23. Write steps to create connection with Postgre SQL database and display the data. ->Step
1: Install Postgresql Extension:
• Ensure that the Postgresql extension for PHP is installed. You can do this by checking your
PHP configuration or installing it using the parkage manager.

step 2: Set up Database connection:


Use the pg_connect function to establish a connection to the Postgresql database by providing
the host, database name, user and password.
Step 3: Execute SQL Query:
•Use the pg_query function to execute SQL queries, such as selecting data from a table.

Step 4: Fetch and Display Data:


Fetch the results from the executed query functions like pg_fetch_assoc or pg_fetch_row.
Display or process the data as needed.
24. List the features of PHP7.
->Improved Performance: PHP7 offers significant performance improvements over previous
versions, making web applications run faster.
2) Error Handling improvements: PHP7 includes Improved error handling with the
introduction. of two new classes for better exception hierarchy.
3) Anonymous classes: PHP 7 introduces support for anonymous classes, allowing the
creation of simple, one-off objects without the need for a separate class declaration.
4) Scalar Type Declarations: The introduction of scalar type declarations allows developers
to specify the expected data type for function parameters and return values.

25. How to pass parameters to a function by reference? Explain with example. Also write its
advantage.
->→In PHP, you can pass parameters to a function by reference using the ampersand (+)
symbol.
This allows the function to modify the original value of the variable passed to it.
Here is an example:
<?php function addTen
(&$hum){
$num+=10;} $value =
5; add Ten ($value);
echo $value; // op:-15
?>

Advantages:-
When a parameter is passed by reference, any changes made to the parameter within the
function affect the original variable outside the function.
This allows for more flexible and dynamic manipulation of data.
Passing by reference avoid's creating unnecessary copies of variables, which can be important
for performance when dealing with large datasets or objects.
Helps to conserve memory compared to passing by value, especially when dealing with large
data structures.

26. What is the difference between index and associative array?


->Index aray
Indexed array is an array with a numeric key.
It is basically an array wherein each of the keys is associated with Its own specific value. They
are like single- column tables.
Example:
Array: Array (
[0]=>5;
[1]=>6;)
Associative array •An associative array is stored in the form of key-value pair.
This type of array is where the key is stored in the numeric, or string format. They
are like two-column tables.
Example:
Array:Array (
[Java]=> Spring Boot
[Python]=> Django
[PHP]=> CodeIgniter)

27. Explain datatypes in PHP.


-> PHP allows eight different types of data types. There are pre-defined, user-defined, and
special data types.The predefined data types are:
Boolean
Integer
Double
String
The user-defined (compound) data types are:
Array
Objects
The special data types are:
NULL resource
1.Integer: Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point
2.Double: Can hold numbers containing fractional or decimal parts including positive and
negative numbers or a number in exponential form
3.String: Hold letters or any alphabets, even numbers are included
4.Boolean: Boolean data types are used in conditional testing. Hold only two values, either
TRUE(1) or FALSE(0).
5.Array: Array is a compound data type that can store multiple values of the same data type
6.Objects: Objects are defined as instances of user-defined classes that can hold both values
and functions and information for data processing specific to the class.
7. NULL: These are special types of variables that can hold only one value i.e., NULL
8. Resources: Resources in PHP are not an exact data type. These are basically used to store
references to some function call or to external PHP resources.

28. What is the use of callback in PHP? Explain with example.


->Callbacks are powerful in PHP as they allow for dynamic behavior and can be used in various
scenarios, such as array manipulation, event handling, and asynchronous operations.
In PHP, a callback refers to passing a function as an argument to another function, allowing the
called function to execute the passed function at a certain point during its execution.
This is commonly used for implementing flexible and reusable code, especially in scenarios
where behavior may vary.
29. Explain constructor and destructor with suitable example
->Constructor
Accepts one or more arguments.
function name is construct() Constructors
can be overloaded.
It has same hame as the class.
Constructor is involved automatically when the object is created.

Destructor
No arguments are passed. Its void.
function name is destruct()
It has same name as the class with prefix ~tilda.
Destructor is involved automatically when the object is destroyed. Destructors
cannot be overloaded.

30. Explain any five functions to sort an array in PHP.


->sort():
The sort() function is the most basic sorting function in PHP. It arranges array elements in
ascending order based on their values.. The sort() function does not preserve the original
keys of the array elements.

rsort():
The rsort() function is similar to the sort() function, but it arranges array elements in
descending order based on their values. Does not preserve the original keys of the array
elements.

• asort():
The asort() function arranges array elements in ascending order based on their values and
preserves the original keys of the away elements.

• arsort():
The arsort() function is similar to the asort () function, but it arranges array elements in
descending order based on their values and preserves the original keys of the array elements.

•ksort():
The ksort() function arranges array elements in ascending order based on their keys. This
function is useful when you want to sort an array based on its keys rather than its values.
31. What is Data type? List different Data types in PHP? Explain any two. a data type is a
classification that specifies which type of value a variable can hold and what operations can
be performed on it.
In PHP, like in many programming languages, there are several data types. Some common data
types in PHP include:

String:Strings in PHP are sequences of characters enclosed within single or double quotes.They
can contain letters, numbers, symbols, and whitespace.
PHP offers various functions for string manipulation such as concatenation, substring
extraction, searching, and replacing.
Array:Arrays in PHP can hold multiple values under a single variable name.
They can store various data types (e.g., integers, strings, objects) and are indexed by numerical
keys starting from 0, or associative arrays with named keys.
PHP provides numerous functions for array manipulation like adding elements, removing
elements, sorting, and merging arrays

32. What is inheritance? Explain with suitable example.


->Inheritance is a concept of accessing the features of one class from another class.
If we inherit the class features into another class, we can access both class properties. We can
extends the features of a class by using'extends' keyword. It supports the concept of
hierarchical classification The parent class is known as base class.
The idea behind using inheritance is all about better management and reusability of code.
Example : <?php class a function fun1(){ echo" javapoint"; } } class b extends a { function
fun2 () { echo "W3school"; }}
$obj = new b();
$obj-> fun1();
?>
33. Write a php script to create user defined functions Xsubstr (string, start [, length]) and
illustrate the same.
34. Explain the different loops in PHP with example.
->Loops: for
loop:
Executes a block of code a specified number of times. for
(initialization; condition; increment/decrement) {
// code to be executed }Example:for
($i = 0; $i < 5; $i++) { echo $i;
}
while loop:
Executes a block of code as long as a specified condition is true.
while (condition) {
// code to be executed
}Example:$i = 0; while ($i
< 5) { echo $i;
$i++;
}
do-while loop:
Similar to a while loop, but the code block is executed at least once before the condition is
tested do {
// code to be executed } while
(condition);Example:$i = 0; do
{ echo $i;
$i++;
} while ($i < 5); foreach loop: Iterates over
arrays and objects.

35. Explain any two functions to retrieve the parameters passed to it in PHP. Explain with
example.
-> func_get_arg(): This function retrieves a specific parameter passed to a function based on its
index. It's useful when you want to access a particular parameter within the function.
func_get_args(): This function retrieves the parameters passed to a function as an indexed
array. It's useful when the number of parameters passed to a function may vary.

37.Write a php script display the student details in table format.


40. How to retrieve information about the parameters passed to user defined function in PHP?
Explain with example.
-> In PHP, you can retrieve information about the parameters passed to a user-defined function
using the ReflectionFunction class.
This class provides methods to inspect the parameters of a function, such as their names,
types, and default values.
When you run this code, it will output information about the parameters of the greet function,
including their names, whether they are optional, and their default values (if any).

41. What is the purpose of break and continue statement? Explain with example. ->
break statement: It terminates the current loop and transfers control to the statement
immediately following the loop. // Example of using break statement for ($i = 0; $i < 10;
$i++) { echo $i . "<br>"; if ($i === 5) { break; // Terminate the loop when $i
equals 5
}
}
continue statement: It skips the rest of the current iteration of a loop and moves to the next
iteration.
// Example of using continue statement for ($i = 0; $i < 5;
$i++) { if ($i === 2) { continue; // Skip the current
iteration when $i equals 2
}
echo $i . "<br>";
}

42. How inheritance is implemented in PHP? Explain how base class methods and properties
are accessed? Give example
-> In PHP, inheritance is implemented using the keyword extends, where a child class extends a
parent class
The child class inherits all the non-private properties and methods from the parent class,
allowing it to reuse and build upon the functionality provided by the parent.
This relationship between classes forms an "is-a" relationship, where the child class is a
specialized version of the parent class.
To access the base class methods or properties from outside the class, they need to be either
public or protected.
Example:
<?php
class Animal{ protected $name;
public function __construct($name) {
$this->name = $name;
}
public function eat(){ echo
$this->name." is eating.";
}}
class Cat extends Animal { public
function meow(){ echo $this-
>name ."says Meow!";
}
public function eat() {
parent::eat (); echo
"Yum yum!";
}}
$mycat = new cat ("Whiskers"); echo
$mycat->name;
$mycat-> eat();
$mycat->meow();
?>

You might also like