PHP - Mohan

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Write a PHP script to find the factorial of a given number.

<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
Output:
Factorial of 4 is 24
Write a PHP script to find the sum of digits of a given number.
<?php
$num = 14597;
$sum=0; $rem=0;
for ($i =0; $i<=strlen($num);$i++)
{
$rem=$num%10;
$sum = $sum + $rem;
$num=$num/10;
}
echo "Sum of digits 14597 is $sum";
?>
Output:
Sum of digits 14597 is 26

Write a PHP script to find whether the given number is a prime ornot.
<?php
function check_prime($num)
{
if ($num == 1)
return 0;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
return 0;
}
return 1;
}
$num = 47;
$flag_val = check_prime($num);
if ($flag_val == 1)
echo "It is a prime number";
else
echo "It is a non-prime number"
?>
Output:
It is a prime number
Write a PHP script to demonstrate the use of break, continue statements using
nested loops.
<?php
// PHP program to break the loop
// Declare an array and initialize it
$array = array( 1, 2, 3, 4, 5, 6, 7 );
// Use foreach loop
foreach ($array as $a) {
if ($a == 5)
break;
else
echo $a . " ";
}
echo "\n";
echo "Loop Terminated";
?>
Output:
2 3 4
Loop Terminated
<?php
// PHP program to break the loop
// Declare an array and initialize it
$array = array( 1, 2, 3, 4, 5, 6, 7 );
// Use foreach loop
foreach ($array as $a) {
if ($a == 5)
Continue;
else
echo $a . " ";
}
echo "\n";
echo "Loop Terminated";
?>
Output:
2 3 4 6 7
Write a PHP script to display the Fibonacci sequence
<?php
$num = 0;
$n1 = 0;
$n2 = 1;
echo "<h3>Fibonacci series for first 12 numbers: </h3>";
echo "\n";
echo $n1.' '.$n2.' ';
while ($num < 10 )
{
$n3 = $n2 + $n1;
echo $n3.' ';
$n1 = $n2;
$n2 = $n3;
$num = $num + 1;
?>

Write a PHP script to create a chessboard.


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>Chess Board using Nested For Loop</h3>
<table width="270px" cellspacing="0px" cellpadding="0px" border="1px">
<!-- cell 270px wide (8 columns x 60px) -->
<?php
for($row=1;$row<=8;$row++)
{
echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if($total%2==0)
{
echo "<td height=30px width=30px bgcolor=#FFFFFF></td>";
}
else
{
echo "<td height=30px width=30px bgcolor=#000000></td>";
}
}
echo "</tr>";
}
?>
</table>
</body>
</html>

Write a PHP script using built-in string function like strstr(), strpos(), substr_count(),
etc...
Strstr()
<!DOCTYPE html>
<html>
<body>
<?php
echo strstr("Hello world!",111);
?>
</body>
</html>
Ouptut:
World!
Strpos()
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("I love php, I love php too!","php");
?>
</body>
</html>
Output:
7
Substr_count()
<!DOCTYPE html>
<html>
<body>
<?php
echo substr_count("Hello world. The world is nice","world");
?>
</body>
</html>
Output:
2
Write a PHP script to transform a string to uppercase, lowercase letters, make a
string’s first character uppercase.
<!DOCTYPE html>
<html>
<body>
<?php
echo strtolower("Hello WORLD.");
echo strtoupper(“hello world”);
echo ucfirst(“HELLO”);
?>
</body>
</html>
Output:
hello world
HELLO WORLD
Hello

Write a PHP script that inserts a new item in an array in any position.
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
</body>
</html>
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )

Write a PHP function to check whether all array values are strings or not.

<?php
function check_strings_in_array($arr)
{
return array_sum(array_map('is_string', $arr)) == count($arr);
}
$arr1 = array('PHP', 'JS', 'Python');
$arr2 = array('SQL', 200, 'MySQL');
var_dump(check_strings_in_array($arr1));
var_dump(check_strings_in_array($arr2));
?>
Output:
Bool(true)
Bool(false)

Write a PHP script to count number of elements in an array and display a range of
arrayelements.
<?php
$array = array("javatpoint", "udemy", "udacity", "coursera", "edureka");
print_r(count($array));
print_r($array);
?>
Output:
5
[0] => javatpoint
[1] => udemy
[2] => udacity
[3] => courser
[4] => edureka

Write a PHP script to sort a multi-dimensional array set by a specific key.


<?php
#declaring an associative array
$arr = array(
array("Name"=>"YASHIKA", "marks"=>22),
array("Name"=>"ASHIKA", "marks"=>67),
array("Name"=>"BASHIKA", "marks"=>87),
array("Name"=>"YASHITA", "marks"=>24),
array("Name"=>"AMAN", "marks"=>55),
array("Name"=>"ANjali", "marks"=>98),
array("Name"=>"YASHIKA", "marks"=>100),
);
#declaring an array to store names
$names = array();
#iterating over the arr
foreach ($arr as $key => $val)
{
#storing the key of the names array as the Name key of the arr
$names[$key] = $val['Name'];

}
#apply multisort method
array_multisort($names, SORT_ASC, $arr);
print_r("Modified Array : ");
print_r($arr);
?>
Output:
Modified Array : Array
(
[0] => Array
(
[Name] => AMAN
[marks] => 55
)
[1] => Array
(
[Name] => ANjali
[marks] => 98
)
[2] => Array
(
[Name] => ASHIKA
[marks] => 67
)
[3] => Array
(
[Name] => BASHIKA
[marks] => 87
)
[4] => Array
(
[Name] => YASHIKA
[marks] => 22
)
[5] => Array
(
[Name] => YASHIKA
[marks] => 100
)
[6] => Array
(
[Name] => YASHITA
[marks] => 24
)
)
Write a PHP script using a function to display the entered string in reverse.
<?php
// PHP program to reverse a string using strrev()
function Reverse($str){
return strrev($str);
}

// Driver Code
$str = "College";
echo Reverse($str)
?>
Output:
egelloC

Write a PHP script using function for sorting words in a block of text by length.
<!DOCTYPE html>
<html>
<body>
<?php
$str = "An example of a long word is: Supercalifragulistic";
echo wordwrap($str,15,"<br>\n");
?>
</body>
</html>
Output
An example of a
long word is:
Supercalifragulistic

Write a PHP script for creating the Fibonacci sequence with recursive function.
<?php
/* Print fiboancci series upto 12 elements. */
$num = 12;
echo "<h3>Fibonacci series using recursive function:</h3>";
echo "\n";
/* Recursive function for fibonacci series. */
function series($num){
if($num == 0){
return 0;
}else if( $num == 1){
return 1;
} else {
return (series($num-1) + series($num-2));
}
}
/* Call Function. */
for ($i = 0; $i < $num; $i++){
echo series($i);
echo "\n";
}
Output:
Fibonacci series using recursive function:
0 1 1 2 3 5 8 13 21 34 55 89

Write a PHP script using pass by value and pass by reference mechanisms in passing
arguments to functions.
Call by Value:
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
Hello

Call by reference:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
Output:
This is Call By Reference

Write a PHP script to demonstrate the defining and using object properties.
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
</body>
</html>
Output
Apple
Banana
Write a PHP script to demonstrate the inheritance.
<!DOCTYPE html>
<html>
<body>
<? php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
</body>
</html>
Output:
Am I a fruit or a berry? The fruit is Strawberry and the color is red.

Write a PHP script to demonstrate the object overloading with _get(), _set(),
and_call().
<?php
class Truck {
public function __get($propertyName) {
echo"The value of'$propertyName'was requested \n";
return"blue";
}// w w w .j a va2s . c o m
}

$truck = new Truck;


$x = $truck->color; // Displays"The value of'color'was requested"
echo"The Truck's color is $x \n"; // Displays"The Truck's color is blue"
$x = $truck->speed;
echo"$x \n";

?>
Output:

Write a PHP script to demonstrate the overloading property accesses with _get()
and _set().
<?php
//
class GFG {
// Location of overloading data
private $data = array();
// Overloading not used here
public $declared = 1;
// Overloading used when accessed
// outside the class
private $hidden = 2;
// Function definition
public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}

// Function definition
public function __get($name) {
echo "Getting '$name: ";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}

$trace = debug_backtrace();
return null;
}
// Function definition
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}

// Definition of __unset function


public function __unset($name) {
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}

// getHidden function definition


public function getHidden() {
return $this->hidden;
}
}

// Create an object
$obj = new GFG;
// Set value 1 to the object variable
$obj->a = 1;
echo $obj->a . "\n";
// Use isset function to check
// 'a' is set or not
var_dump(isset($obj->a));
// Unset 'a'
unset($obj->a);
var_dump(isset($obj->a));
echo $obj->declared . "\n\n";
echo "Private property are visible inside the class ";
echo $obj->getHidden() . "\n\n";
echo "Private property are not visible outside of class\n";
echo $obj->hidden . "\n";
?>
Output:
Setting 'a' to '1'
Getting 'a: 1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1
Private property are visible inside the class 2
Private property are not visible outside of class
Getting 'hidden:

Write a PHP script to demonstrate the method overloading and method overriding
mechanisms.
Overloading:
<?php
class Shape {
const PI = 3.142 ;
function __call($name,$arg){
if($name == 'area')
switch(count($arg)){
case 0 : return 0 ;
case 1 : return self::PI * $arg[0] ;
case 2 : return $arg[0] * $arg[1];
}
}
}
$circle = new Shape();
echo $circle->area(3);
$rect = new Shape();
echo $rect->area(8,6);
?>
Output:
9.42648

Overriding:
<?php
class Base {
function display() {
echo "\nBase class function declared final!";
}
function demo() {
echo "\nBase class function!";
}
}
class Derived extends Base {
function demo() {
echo "\nDerived class function!";
}
}
$ob = new Base;
$ob->demo();
$ob->display();
$ob2 = new Derived;
$ob2->demo();
$ob2->display();
?>
Output:
Base class function!
Base class function declared final!
Derived class function!
Base class function declared final!

Write a PHP script to demonstrate the use of final classes and final methods.
<?php
class BaseClass{
final function calculate($val1,$val2){
$sum = $val1+$val2;
echo "Sum of given no=".$sum;
}
}
class ChildClass extends BaseClass{
function calculate($x,$y){
$mult=$val1*$val2;
echo "Multiplication of given no=".$mult;
}
}
$obj= new ChildClass();
$obj->show(10,10);
?>
Output:
PHP Fatal error: Cannot override final method BaseClass::calculate()

<?php
final Class BaseClass{
function printData($val1,$val2){
$add=$val1+$val2;
echo "Sum of given no=".$s;
}
}
class Child extends BaseClass{
function printData($val1,$val2){
$m=$val1*$val2;
echo "Multiplication of given no=".$m;
}
}
$obj= new Child();
$obj->printData(20,20);
?>
Output
PHP Fatal error: Class Child may not inherit from final class (BaseClass)

Write a PHP script to demonstrate the user interfaces


<?php
Interface MyInterface {
public function getName();
public function getAge();
}
class MyClass implements MyFirstInterface{
public function getName() {
echo "My name A".'<br>';
}
public function getAge(){
echo "My Age 12";
}
}
$obj = new MyClass;
$obj->getName();
$obj->getAge();
?>
Output.
My name A
My Age 12

Write a PHP script using constructors and destructors.


<?PHP
class Tree
{
function Tree()
{
echo "Its a User-defined Constructor of the class Tree";
}

function __construct()
{
echo "Its a Pre-defined Constructor of the class Tree";
}
}

$obj= new Tree();


?>
Output:
Its a Pre-defined Constructor of the class Tree

Write a PHP application to handling HTML forms with PHP script.


<!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
Welcome.php
<?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

Write a PHP script to create a file, write data into file and display the file’s data.
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Write a PHP script to check and change file permissions, copying, renaming and
deleting files.
<?php
$filename = 'readme.txt';
$functions = [
'is_readable',
'is_writable',
'is_executable'
];
foreach ($functions as $f) {
echo $f($filename) ? 'The file ' . $filename . $f : '';
}

File Permissions
<?php
$permissions = fileperms('readme.txt');
echo substr(sprintf('%o', $permissions), -4); //0666
?>

Write a PHP application for connecting to MySQL and reading data from database
table.

Write a PHP application for inserting, updating, deleting records in the database
table.
Write a PHP application for student registration form.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy