PHP Sy Bca
PHP Sy Bca
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>
The require() function will stop the execution of the script when
an error occurs.
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.
In case of post request, large amount of data can be sent because data is sent in body.
4) Get request is idempotent . It means second request will be ignored until response of first
request is delivered
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
$_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.
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.
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.
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.
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; };
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.
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.
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.
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
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.
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();
?>