0% found this document useful (0 votes)
12 views17 pages

Q2 and notes php

The document provides an overview of various PHP concepts including constants vs variables, foreach loops, types of arrays, form submission methods, sessions, variable types, conditional statements, cookies, string functions, and built-in array functions. It also includes code examples for checking leap years, defining interfaces, calculating areas and volumes, reversing arrays, and checking voting eligibility. Additionally, it discusses the features of PHP and the differences between for and foreach loops.

Uploaded by

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

Q2 and notes php

The document provides an overview of various PHP concepts including constants vs variables, foreach loops, types of arrays, form submission methods, sessions, variable types, conditional statements, cookies, string functions, and built-in array functions. It also includes code examples for checking leap years, defining interfaces, calculating areas and volumes, reversing arrays, and checking voting eligibility. Additionally, it discusses the features of PHP and the differences between for and foreach loops.

Uploaded by

sushanttandale6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

a)What are differences between PHP constant

and variable ?
Constant Variable:
 A constant  A variable
is a name or is a name for
an identifier a storage
for a simple location that
value. holds data
that can be
changed
during script
execution.
 The value  Variables
cannot be are declared
changed using the
during the dollar sign ($)
script followed by
execution. the variable
name.
 Constants  Variables
are defined can have
using the their values
define() changed at
function or any time.
the const
keyword.
 Constants  Variables
do not are local to
require a the scope in
dollar sign ($) which they
before their are defined,
name. unless
declared
global.

b)explain the syntax foreach loop with


example.
In PHP, the foreach loop is used to iterate
over arrays and objects. It provides an easy
way to loop through each value in an array
without the need for a counter variable. The
basic syntax of a foreach loop is:
foreach ($array as $value) {
// Code to execute for each value
}
c) what are the different types of arrays in
PHP?
Indexed Arrays: Arrays with numeric
indexes.
Associative Arrays: Arrays with named
keys.
Multidimensional Arrays: Arrays
containing one or more arrays.
d) Explain

methods to
submit form.
 GET Method: Data is sent appended to the
URL as query strings. It is visible to
everyone and has length limitations.
 POST Method: Data is sent in the request
body. It is not visible in the URL and has no
size limitations.P
e)what is a session in PHP? Explain it.
A session in PHP is a way to store
information (in variables) to be used across
multiple pages. Unlike a cookie, the
information is not stored on the user's
computer.
 Starting a Session:
php
session_start();
 Setting Session Variables:
php
$_SESSION["username"] = "John";
 Accessing Session Variables:
php
echo $_SESSION["username"];
 Ending a Session:
php
session_unset(); // remove all session
variables
session_destroy(); // destroy the session
a) What are the different types of PHP
variables?

 Integer: Whole numbers without a decimal


point.
 Float (Double): Numbers with a decimal
point or in exponential form.
 String: Sequence of characters.
 Boolean: Represents two possible states:
TRUE or FALSE.
 Array: Stores multiple values in a single
variable.
 Object: Instances of classes that store data
and functions.
 NULL: A variable with no value.
 Resource: Special variable holding a
reference to an external resource (e.g.,
database connection).
b) What is the difference
between GET and POST
method?
 GET:
 Data is sent via URL parameters.
 Limited amount of data can be sent
(due to URL length restrictions).
 Data is visible in the URL, hence less
secure.
 Can be bookmarked and cached.

 POST:
 Data is sent via the request body.
 Larger amounts of data can be sent.
 Data is not visible in the URL, making it
more secure.
 Cannot be bookmarked or cached.
c) Explain if ...... then else in PHP.
In PHP, the if...then...else statement is used
for conditional execution of code blocks.
Here's a breakdown of its structure and
functionality:
Explanation
1. Condition: This is an expression that evaluates to either
true or false. It can be any expression that PHP can
evaluate to a boolean value.
2. Code Block for if: If the condition evaluates to true,
the code inside the first block (following if) will be
executed.
3. Code Block for else: If the condition evaluates to
false, the code inside the else block will be executed
instead.
d) Explain cookies in PHP
  Cookies are small files that the server
embeds on the user's computer.
  They are used to store data about the
user for tracking and personalization
purposes.
e) Explain any two string functions in PHP.

 strlen(): Returns the length of a string.


$str = "Hello, world!";
echo strlen($str); // Output: 13

 str_replace(): Replaces all occurrences of


a search string with a replacement string.

$str = "Hello, world!";


$newstr = str_replace("world", "PHP", $str);
echo $newstr; // Output: Hello, PHP!
a) Write a PHP Program to check whether
given year is leap year or not (use if else)
<?php
function isLeapYear($year) {
if (($year % 4 == 0 && $year % 100 != 0)
|| ($year % 400 == 0)) {
return true;
} else {
return false;
}
}
$year = 2024;
if (isLeapYear($year)) {
echo "$year is a leap year.";
} else {
echo "$year is not a leap year.";
}
?>
b) Write a PHP script to define an interface
which has methods area () volume ().
<?php
interface Shape {
public function area();
public function volume();
}
?>
c) constant PI. Create a class cylinder which
implements this interface and calculate
area and volume
<?php
interface Shape {
public function area();
public function volume();
}
class Cylinder implements Shape {
const PI = 3.14159;
private $radius;
private $height;
public function __construct($radius,
$height) {
$this->radius = $radius;
$this->height = $height;
}
public function area() {
return 2 * self::PI * $this->radius *
($this->radius + $this->height);
}
public function volume() {
return self::PI * pow($this->radius, 2) *
$this->height;
}
}
$cylinder = new Cylinder(3, 5);
echo "Area of the cylinder: " . $cylinder-
>area() . "\n";
echo "Volume of the cylinder: " . $cylinder-
>volume() . "\n";
?>
d) What are the built in functions of string?
PHP provides a wide range of built-in
functions for string manipulation. Some of
the commonly used string functions are:
 strlen(): Returns the length of a string.
 strpos(): Finds the position of the first
occurrence of a substring in a string.
 str_replace(): Replaces all occurrences of
a search string with a replacement string.
 substr(): Returns a part of a string.
 strtolower(): Converts a string to
lowercase.
 strtoupper(): Converts a string to
uppercase.
 trim(): Strips whitespace (or other
characters) from the beginning and end
of a string.
 explode(): Splits a string by a string.
 implode(): Joins array elements with a
string.
 strcmp(): Compares two strings.
e) Write a PHP program to reverse an array
<?php
function reverseArray($array) {
$reversedArray = array();
for ($i = count($array) - 1; $i >= 0; $i--) {
$reversedArray[] = $array[$i];
}
return $reversedArray;
}
$array = array(1, 2, 3, 4, 5);
$reversedArray = reverseArray($array);
echo "Original array: ";
print_r($array);
echo "Reversed array: ";
print_r($reversedArray);
?>
a) write are the features of php.
Performance: PHP scripts typically run
efficiently and can handle a large number of
requests per second.
Ease of Use: PHP is relatively easy to learn
and has a simple and straightforward syntax.
Open Source: PHP is open-source, meaning
it's free to use and has a large community of
developers who contribute to its continuous
improvement.
b)write
a php script to find the sum of digits of
a number.
<?php
function sumOfDigits($number) {
$sum = 0;
while ($number > 0) {
$sum += $number % 10;
$number = floor($number / 10);
}
return $sum;
}
$number = 12345;
echo "The sum of the digits of $number is: " .
sumOfDigits($number);
?>
c) explain
for loop and foreach loop with
example.
The for loop is used when you know in
advance how many times you want to
execute a statement or a block of
statements. It is commonly used for iterating
over a sequence (like an array).
Example:
<?php
for ($i = 0; $i < 5; $i++) {
echo "The number is: $i <br>";
}
?>
The foreach loop is used to iterate over
arrays. It provides an easy way to access
array elements without needing an index
counter.
Example:
<?php
$colors = array("red", "green", "blue",
"yellow");
foreach ($colors as $color) {
echo "The color is: $color <br>";
}
?>
d)explain cookies in php.
Cookies are small pieces of data that a server
sends to the user's web browser. The browser
may store these cookies and send them back
to the same server with subsequent
requests. Cookies are often used to store
user preferences, session information, or
track user behavior.
e) explain any two built-in array functions in
php.
The array_merge() function merges one or
more arrays into one array.
Example:
array_merge(array1, array2, ...);

The array_push() function inserts one or more


elements at the end of an array.
Example:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
a) What is the difference between for and
for each in PHP?
For For each
 A for loop is  A foreach loop
used to iterate a is specifically
set number of used to iterate
times. over arrays.
 It requires an  It does not
initialization, a require explicit
condition, and an initialization,
increment/decrem condition, or
ent statement. increment/decre
ment
statements.
Syntax: Syntax:
for (initialization; foreach ($array
condition; as $value) {
increment/decrem // code to be
ent) { executed
// code to be }
executed // or with key-
} value pairs
foreach ($array
as $key =>
$value) {
// code to be
executed
}

b) What is season in php? Explain it.


In PHP, the term "season" doesn't refer to
any specific built-in feature or concept within
the language itself. However, if you're
referring to "season" in the context of a web
application or a specific PHP project, it could
mean different things depending on the
context.

c) Write a script to display the total and


percentage of Marks of Subject (Out of 100)
Data structure, Digital Marketing, PHP, SE,
and Big Data.
<?php
// Marks out of 100 for each subject
$dataStructure = 85;
$digitalMarketing = 78;
$php = 90;
$se = 88;
$bigData = 95;
// Calculate total marks
$totalMarks = $dataStructure +
$digitalMarketing + $php + $se + $bigData;
// Calculate percentage
$percentage = ($totalMarks / 500) * 100;
// Display results
echo "Total Marks: " . $totalMarks . "<br>";
echo "Percentage: " . $percentage .
"%<br>";
?>
d) explain cookies in php.
Cookies are small files stored on a user's
computer. They are used to remember
information about the user across different
pages of a website or between visits. In PHP,
cookies are created using the setcookie()
function and retrieved using the $_COOKIE
superglobal.
 Custom Application Logic: If you're working
on a project that deals with seasonal data or
features (like a shopping website with
seasonal sales, a blog with seasonal content,
etc.), "season" could be a custom-defined
concept within the application. For example,
you might have a PHP class or function that
determines the current season based on the
date and adjusts the behavior or display of
your application accordingly.
 Configuration or Data: In some
applications, "season" might be a
configuration setting or part of the data
model. For instance, if you're building an
application for a sports league, "season"
could refer to different seasons of the league
and might be stored in a database, with PHP
code used to manage or display this data.
 Naming Convention: "Season" could also
be part of a naming convention for variables,
classes, or functions in your codebase. For
example, you might have a Season class that
encapsulates all the properties and methods
related to a particular season of a game,
event, or other cyclical activity.
e) Write a php program to check whether
Entertainment age from user is allowed for
vote or not.
<?php
// Function to check voting eligibility
function checkVotingEligibility($age) {
if ($age >= 18) {
return "You are allowed to vote.";
} else {
return "You are not allowed to vote.";
}
}

// Get age from user input (assuming a form


submission)
if ($_SERVER["REQUEST_METHOD"] ==
"POST") {
$age = $_POST["age"];
echo checkVotingEligibility($age);
}
?>
<!-- HTML form to get user age input -->
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF'];?>">
Enter your age: <input type="text"
name="age">
<input type="submit">
</form>
</body>
</html>

You might also like