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

lab internal 1

The document provides a comprehensive overview of PHP programming concepts, including operators, conditional statements, loops, functions, arrays, classes, and objects. It features code examples for each concept, demonstrating their usage and functionality. Additionally, it covers advanced topics such as recursion, multidimensional arrays, and calculating averages and grades for student marks.

Uploaded by

Riya Juneja
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)
5 views

lab internal 1

The document provides a comprehensive overview of PHP programming concepts, including operators, conditional statements, loops, functions, arrays, classes, and objects. It features code examples for each concept, demonstrating their usage and functionality. Additionally, it covers advanced topics such as recursion, multidimensional arrays, and calculating averages and grades for student marks.

Uploaded by

Riya Juneja
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
You are on page 1/ 9

Spaceship Operator

<?php
echo 10 <=> 20; // Output: -1 (10 is less than 20)
echo 20 <=> 20; // Output: 0 (Both are equal)
echo 30 <=> 20; // Output: 1 (30 is greater than 20)
?>
Bitwise Operators
<?php
$a = 5; // Binary: 0101
$b = 3; // Binary: 0011

echo $a & $b; // Output: 1 (Binary: 0001)


echo $a | $b; // Output: 7 (Binary: 0111)
echo $a ^ $b; // Output: 6 (Binary: 0110)
echo ~$a; // Output: -6 (Inverts bits)
echo $a << 1; // Output: 10 (Binary: 1010, Left shift)
echo $a >> 1; // Output: 2 (Binary: 0010, Right shift)
?>
Constant
<?php
define("GREETING", "hello world!");
echo GREETING;
?>
Conditional Statements
if-else Statement
<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0)))
{
echo "$year is a leap year.";
}
else
{
echo "$year is not a leap year.";
}
?>
if-elseif-else Statement
<?php
$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} elseif ($score >= 50) {
echo "Grade: C";
} else {
echo "Grade: F";
}
?>
Switch Statement
<?php
$day = "Monday";

switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is near!";
break;
case "Sunday":
echo "It's a holiday!";
break;
default:
echo "It's a normal day.";
}
?>
Loops
for Loop
<?php
for ($i = 1; $i <= 3; $i++) {
echo "Number: $i <br>";
}
?>
while Loop
<?php
$num = 1;
while ($num <= 3) {
echo "Count: $num <br>";
$num++;
}
?>
do-while Loop
<?php
$x = 5;
do {
echo "Value: $x <br>";
$x++;
} while ($x < 5);
?>
foreach Loop (For Arrays)
<?php
$fruits = array("Apple", "Banana", "Mango");

foreach ($fruits as $fruit) {


echo "$fruit <br>";
}
?>
Function
1)
<?php
function sayHello($name) {
echo "Hello, $name!";
}

sayHello("daksh");
?>
2) Return value
<?php
function add($a, $b) {
return $a + $b; // Returns the sum
}

$result = add(5, 7);


echo "The sum is: $result";
?>
3) Default parameter
<?php
function welcome($user = "Guest") {
echo "Welcome, $user!<br>";
}

welcome("daksh");
welcome(); // Uses default value "Guest"
?>
3) Variable-Length Argument
<?php
function sumNumbers(...$numbers) {
return array_sum($numbers);
}

echo sumNumbers(2, 4, 6, 8); // Output: 20


?>
4) Passing Arguments by Reference (&)
<?php
function doubleValue(&$num) {
$num *= 2;
}

$value = 10;
doubleValue($value);
echo "Doubled Value: $value";
?>
5) Anonymous Functions (Lambda)
<?php
$greet = function($name) {
return "Hello, $name!";
};

echo $greet("daksh");
?>
Arrays
Numeric (Indexed) Arrays
<?php
// Method 1: Using array()
$fruits = array("Apple", "Banana", "Mango");

// Method 2: Using []
$fruits = ["Apple", "Banana", "Mango"];

// Accessing array elements


echo $fruits[0]; // Output: Apple
?>

Looping Through a Numeric Array

foreach ($fruits as $fruit) {


echo $fruit . "<br>";
}

Associative Arrays
<?php
$marks = [
"Math" => 95,
"English" => 88,
"Science" => 92
];

// Accessing values using keys


echo $marks["English"]; // Output: 88
?>

Looping Through an Associative Array

foreach ($marks as $subject => $score) {


echo "Subject: $subject, Score: $score<br>";
}
?>

Multidimensional
<?php
$students = [
["daksh", 22, "BCA"],
["John", 21, "BBA"],
["Sara", 23, "MCA"]
];

// Accessing elements
echo $students[0][0]; // Output: Daksh
echo $students[1][2]; // Output: BBA
?>

Looping Through a Multidimensional Array

foreach ($students as $student) {


echo "Name: $student[0], Age: $student[1], Course: $student[2]<br>";
}
Sorting Array

1. Sorting Numeric (Indexed) Arrays

Ascending Order (sort())

<?php
$numbers = [5, 3, 8, 1, 9];
sort($numbers);

print_r($numbers);
?>

Descending Order (rsort())

<?php
$numbers = [5, 3, 8, 1, 9];
rsort($numbers);

print_r($numbers);
?>

2. Sorting Associative Arrays

Sort by Values (Ascending) – asort()

<?php
$ages = ["Daksh" => 22, "John" => 19, "Sara" => 25];
asort($ages);

print_r($ages);
?>
Sort by Values (Descending) – arsort()

<?php
$ages = ["Daksh" => 22, "John" => 19, "Sara" => 25];
arsort($ages);

print_r($ages);
?>

Sort by Keys (Ascending) – ksort()

<?php
$students = ["Daksh" => 95, "John" => 88, "Sara" => 92];
ksort($students);

print_r($students);
?>

Sort by Keys (Descending) – krsort()

<?php
$students = ["Daksh" => 95, "John" => 88, "Sara" => 92];
krsort($students);

print_r($students);
?>
Class
<?php
class Car {
// Properties (variables)
public $brand;
public $color;

// Method (function)
public function displayInfo() {
echo "This car is a $this->color $this->brand.";
}
}
?>
Object
<?php
$myCar = new Car(); // Create an object
$myCar->brand = "Tesla";
$myCar->color = "Red";

$myCar->displayInfo(); // Output: This car is a Red Tesla.


?>
Constructor Method (__construct())
<?php
class Car {
public $brand;
public $color;

// Constructor method
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}

public function displayInfo() {


echo "This car is a $this->color $this->brand.";
}
}
// Create objects with constructor
$car1 = new Car("BMW", "Black");
$car2 = new Car("Audi", "Blue");

$car1->displayInfo(); // Output: This car is a Black BMW.


$car2->displayInfo(); // Output: This car is a Blue Audi.
?>
Biggest Element in Array
<?php
// Define an array
$array = [3, 5, 7, 2, 8, 1, 6];

// Initialize the first element as the largest


$largest = $array[0];

// Loop through the array to compare each element


for ($i = 1; $i < count($array); $i++) {
if ($array[$i] > $largest) {
$largest = $array[$i];
}
}
echo "The largest number is: " . $largest;
?>
Factorial
<?php
// Define the number
$number = 5;

// Initialize the factorial variable to 1


$factorial = 1;

// Loop to calculate the factorial


for ($i = 1; $i <= $number; $i++) {
$factorial *= $i; // Multiply the factorial by the current number
}
echo "The factorial of " . $number . " is: " . $factorial;
?>
Factorial Using Recursion
<?php
function factorial($n) {
if ($n == 0 || $n == 1) {
return 1; // Base case
}
return $n * factorial($n - 1); // Recursive call
}
$num = 5;
echo "Factorial of $num is: " . factorial($num);
?>
Fibonacci
<?php
// Function to generate Fibonacci series
function fibonacci($n) {
$a = 0; // First number
$b = 1; // Second number
echo "Fibonacci Series up to $n terms: \n";

for ($i = 0; $i < $n; $i++) {


echo $a . " ";
$next = $a + $b;
$a = $b;
$b = $next;
}
}
// Number of terms in Fibonacci series
$num = 10;
fibonacci($num); // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
?>
Number of Digits
<?php
function countDigits($number) {
// Handle negative numbers
if ($number < 0) {
$number = abs($number);
}
// Special case for zero
if ($number == 0) {
return 1;
}
$count = 0;
// Loop to divide the number by 10 until it becomes zero
while ($number > 0) {
$number = (int)($number / 10); // Remove last digit
$count++; // Increment digit count
}
return $count;
}
$number = 12345;
echo "Number of digits in $number is: " . countDigits($number);
?>
Multidimensional Associative Array
<?php
// Multidimensional associative array
$students = array(
"student1" => array(
"name" => "Alice",
"age" => 20,
"marks" => array("Math" => 85, "Science" => 90)
),
"student2" => array(
"name" => "Bob",
"age" => 22,
"marks" => array("Math" => 78, "Science" => 88)
),
"student3" => array(
"name" => "Charlie",
"age" => 21,
"marks" => array("Math" => 92, "Science" => 95)
)
);

// Looping through the array


foreach ($students as $key => $student) {
echo ucfirst($key), ":- Name: " . $student["name"] . ", Age: " . $student["age"] . "<br>";
echo "Marks: " . $student["marks"] ["Math"] . " in Math, " . $student["marks"] ["Science"] . "
in Science<br><br>";
}
?>
Output
Student1:- Name: Alice, Age: 20
Marks: 85 in Math, 90 in Science

Student2:- Name: Bob, Age: 22


Marks: 78 in Math, 88 in Science

Student3:- Name: Charlie, Age: 21


Marks: 92 in Math, 95 in Science
Student Marks with name average and grade Associative Array

<?php
// Simple array of students with their marks
$students = [
['name' => 'Alice', 'marks' => ['Math' => 85, 'Science' => 78, 'English' => 92]],
['name' => 'Bob', 'marks' => ['Math' => 67, 'Science' => 74, 'English' => 70]],
['name' => 'Charlie', 'marks' => ['Math' => 90, 'Science' => 88, 'English' => 95]],
];

// Function to calculate average marks


function calculateAverage($marks) {
return array_sum($marks) / count($marks);
}

// Function to assign a grade based on the average


function getGrade($average) {
if ($average >= 90) {
return 'A';
} elseif ($average >= 80) {
return 'B';
} elseif ($average >= 70) {
return 'C';
} elseif ($average >= 60) {
return 'D';
} else {
return 'F';
}
}

// Loop through each student, calculate average and grade, then display the results
foreach ($students as $student) {
$average = calculateAverage($student['marks']);
$grade = getGrade($average);
echo $student['name'] . " - Average: " . round($average, 2) . ", Grade: " . $grade . "<br>";
}
?>
Output
Alice - Average: 85, Grade: B
Bob - Average: 70.33, Grade: C
Charlie - Average: 91, Grade: A

Class and Object (Rectangle area & perimeter)


<?php
class Rectangle
{
// Declare properties
public $length = 10;
public $width = 5;

// Method to get the perimeter


public function getPerimeter(){
return (2 * ($this->length + $this->width));
}

// Method to get the area


public function getArea(){
return ($this->length * $this->width);
}

public function showResult(){


echo "Length of Rectangle: " . $this->length . "<br>";
echo "Width of Rectangle: " . $this->width . "<br>";
echo "Perimeter of Rectangle: " . $this->getPerimeter() . "<br>";
echo "Area of Rectangle: " . $this->getArea() . "<br>";
}
}
$rec = new Rectangle();
$rec->showResult();
?>

You might also like