[go: up one dir, main page]

0% found this document useful (0 votes)
21 views7 pages

PHP Practical Code

The document contains various PHP code snippets demonstrating fundamental programming concepts such as grading using switch statements, summing numbers, creating multiplication tables, and handling arrays. It also covers object-oriented programming with classes, inheritance, and database operations for CRUD functionality. Additionally, it includes form handling with validation and data display in PHP.
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)
21 views7 pages

PHP Practical Code

The document contains various PHP code snippets demonstrating fundamental programming concepts such as grading using switch statements, summing numbers, creating multiplication tables, and handling arrays. It also covers object-oriented programming with classes, inheritance, and database operations for CRUD functionality. Additionally, it includes form handling with validation and data display in PHP.
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/ 7

1.

Grade using switch


<?php
$marks = 85;
switch (true) {
case ($marks >= 90):
echo "Grade: A";
break;
case ($marks >= 75):
echo "Grade: B";
break;
case ($marks >= 50):
echo "Grade: C";
break;
default:
echo "Fail";
}
?>

2. Sum of first 10 even numbers using while


<?php
$sum = 0;
$i = 1;
$count = 0;
while ($count < 10) {
if ($i % 2 == 0) {
$sum += $i;
$count++;
}
$i++;
}
echo "Sum: $sum";
?>

3. Sum of digits
<?php
$num = 1234;
$sum = 0;
while ($num != 0) {
$sum += $num % 10;
$num = (int)($num / 10);
}
echo "Sum of digits: $sum";
?>

4. Multiplication table of number 'n'


<?php
$n = 5;
for ($i = 1; $i <= 10; $i++) {
echo "$n x $i = " . ($n * $i) . "<br>";
}
?>

5. Multiplication table of 1 to 5
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Table of $i<br>";
for ($j = 1; $j <= 10; $j++) {
echo "$i x $j = " . ($i * $j) . "<br>";
}
echo "<br>";
}
?>

6. Foreach loop with arrays


<?php
$indexed = [10, 20, 30];
$assoc = ["a" => "Apple", "b" => "Banana"];

foreach ($indexed as $value) {


echo "$value<br>";
}

foreach ($assoc as $key => $value) {


echo "$key => $value<br>";
}
?>

7. Associative array of students


<?php
$students = ["John" => "A", "Jane" => "B"];
foreach ($students as $name => $grade) {
echo "$name has grade $grade<br>";
}
?>

8. Multidimensional array - students


<?php
$students = [
["Name" => "John", "Roll" => 1, "Marks" => 90],
["Name" => "Jane", "Roll" => 2, "Marks" => 85]
];
foreach ($students as $student) {
echo "Name: {$student['Name']}, Roll: {$student['Roll']}, Marks:
{$student['Marks']}<br>";
}
?>

9. Multidimensional array - users


<?php
$users = [
["Name" => "John", "Email" => "john@example.com", "Mobile" => "1234567890",
"Address" => "NY"],
["Name" => "Jane", "Email" => "jane@example.com", "Mobile" => "0987654321",
"Address" => "LA"]
];
foreach ($users as $user) {
echo "Name: {$user['Name']}, Email: {$user['Email']}, Mobile: {$user['Mobile']},
Address: {$user['Address']}<br>";
}
?>
10. String length and word count without str_word_count()
<?php
$str = "Hello world from PHP";
$length = strlen($str);
$words = preg_split('/\s+/', trim($str));
$word_count = count($words);
echo "Length: $length<br>";
echo "Word Count: $word_count";
?>

11. Parameterized sum function


<?php
function sum($a, $b) {
return $a + $b;
}
echo "Sum: " . sum(10, 20);
?>

12. Anonymous function


<?php
$print = function($msg) {
echo $msg;
};
$print("Hello from anonymous function!");
?>

13. Single Inheritance


<?php
class Student {
public $name = "John";
}

class Test1 extends Student {


public $marks = 85;

public function show() {


echo "Name: $this->name, Marks: $this->marks";
}
}

$obj = new Test1();


$obj->show();
?>

14. Multilevel Inheritance


<?php
class Student {
public $name = "John";
}

class Tests extends Student {


public $test1 = 80;
public $test2 = 90;
}

class Result extends Tests {


public function show() {
$avg = ($this->test1 + $this->test2) / 2;
echo "Name: $this->name, Test1: $this->test1, Test2: $this->test2, Average:
$avg";
}
}

$obj = new Result();


$obj->show();
?>

15. Class Introspection


<?php
class Sample {
public $x;
private $y;

function test() {}
}

$ref = new ReflectionClass('Sample');


echo "Class Name: " . $ref->getName() . "<br>";
print_r($ref->getProperties());
print_r($ref->getMethods());
?>

16. Product class with constructor


<?php
class Product {
public $id, $name, $price;

function __construct($id, $name, $price) {


$this->id = $id;
$this->name = $name;
$this->price = $price;
}
}

$products = [
new Product(1, "Pen", 10),
new Product(2, "Book", 50),
new Product(3, "Pencil", 5)
];

$total = 0;
foreach ($products as $product) {
$total += $product->price;
}
echo "Total Price: $total";
?>
17. Serialize and Unserialize
<?php
$arr = ["name" => "John", "age" => 25];
$ser = serialize($arr);
echo "Serialized: $ser<br>";
$unser = unserialize($ser);
print_r($unser);
?>

18. Registration form with validation


<form method="post">
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
Phone: <input type="text" name="phone"><br>
<input type="submit" name="submit">
</form>

<?php
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$phone = $_POST['phone'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) echo "Invalid email<br>";
if (strlen($password) < 6) echo "Password too short<br>";
if (!preg_match('/^[0-9]{10}$/', $phone)) echo "Invalid phone<br>";
}
?>

19. Registration form with data display


<form method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit" name="submit">
</form>

<?php
if (isset($_POST['submit'])) {
echo "Name: " . $_POST['name'] . "<br>Email: " . $_POST['email'];
}
?>

20. Student DB CRUD (Create, Read, Update, Delete)


<?php
$conn = new mysqli("localhost", "root", "", "school");

// Insert
$conn->query("INSERT INTO students (name, marks) VALUES ('John', 90)");

// Read
$result = $conn->query("SELECT * FROM students");
while ($row = $result->fetch_assoc()) {
echo "{$row['name']} - {$row['marks']}<br>";
}
// Update
$conn->query("UPDATE students SET marks = 95 WHERE name = 'John'");

// Delete
$conn->query("DELETE FROM students WHERE name = 'John'");
?>

21. Student DB - Insert, Read, Delete


<?php
$conn = new mysqli("localhost", "root", "", "school");

// Insert
$conn->query("INSERT INTO students (name, marks) VALUES ('Jane', 85)");

// Read
$result = $conn->query("SELECT * FROM students");
while ($row = $result->fetch_assoc()) {
echo "{$row['name']} - {$row['marks']}<br>";
}

// Delete
$conn->query("DELETE FROM students WHERE name = 'Jane'");
?>

You might also like