Anda di halaman 1dari 46

Php small Program for beginners

Quest : Print
1
12
123
1234
12345
<?php
for ($i=1; $i<=5; $i++)
{
for($j=1;$j<=$i;$j++)
{
echo $j." ";
}
echo "<br/>";
}
?>

Output:

12
123
1234
12345

Print
*
**
***
****
*****
<?php
for ($i=1; $i<=5; $i++)
{
for ($k=5; $k>$i; $k--)
{

//print one space throgh html ;


echo " ";
}
for($j=1;$j<=$i;$j++)
{
echo "*";
}
echo "<br/>";
}
?>

Output:
*
**
***
****
*****

What will be output of following program :


<?php
$x=89;
define('ABC',$x+1);
$x=$x+ABC;
echo ABC."<br/>";
echo $x;
?>
ans :
90
179

Find sum of even number between 1 to 100

<?php
$sum=0;
for($i=1;$i<=100;$i++)
{
if($i%2==0)
{
$sum=$sum+$i;
}
}
echo $sum;
?>
Output: 2550

Check given number is even or odd


<?php
$num=$_POST['n'];
if($num%2==0)
{
echo $num." is even number";
}
else
{
echo $num." is odd number";
}
?>
Check given character is vowel or consonent.
<?php
$char=$_POST['ch'];
if($char=="a")
{
echo $char." is vowel";
}
elseif($char=="e")
{
echo $char." is vowel";
}
elseif($char=="i")
{
echo $char." is vowel";
}
elseif($char=="o")
{

echo $char." is vowel";


}
elseif($char=="u")
{
echo $char." is vowel";
}
else
{
echo $char. "is consonent";
}
?>

Write a program to print your name 10 times.


<?php
$name="Pooja";
for ($i=1; $i<=10; $i++)
{
echo "My Name is: ".$name."<br/>"
}
?>

Output: My Name is Pooja


My Name is Pooja
My Name is Pooja
My Name is Pooja
My Name is Pooja

Find the sum of 1 to 100.

<?php
$sum=0;
for ($i=1; $i<=100; $i++)
{
$sum=$sum+$i;
}
echo $sum;
?>

Output: 5050

Find all even numbers between 1 to 100 using loop(Not use


conditional statement).
<?php
for ($i=2; $i<=100; $i+=2)
{
echo $i." ";
}
?>

Output: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42
44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86
88 90 92 94 96 98 100

Find all odd numbers between 1 to 100 using loop.

<?php
for ($i=1; $i<=99; $i+=2)
{
echo $i." ";
}
?>

Output: 1 3 5 7 9 ... 99

Find the Sum of even and odd numbers between 1 to 100.


<?php
for ($i=1; $i<=100; $i++)
{
if($i%2==0)
{
@$even=$even+$i;
}
else
{
@$odd=$odd+$i;
}
}
echo "Sum of even numbers=".$even."<br/>";
echo "Sum of odd numbers=".$odd;
?>

Output:

Sum of even numbers=2550

Sum of odd numbers=2500

Add two numbers using loop(Not use + operator).


<?php
@$f=$_GET['f'];
@$s=$_GET['s'];
for ($i=1; $i<=$s; $i++)
{
$f++;
}
echo "Sum of given numbers=".$f;
?>
<body>
<form>
Enter first number
<input type="text" name="f"><br/>
Enter Second number
<input type="text" name="s"><br/>
<input type="submit" value="add">
</form>
</body>

Output:

Sum of given numbers=1000

Enter first number


Enter Second number

Subtract two numbers using loop(Not use - operator).

<?php
@$f=$_GET['f'];
@$s=$_GET['s'];
for ($i=1; $i<=$s; $i++)
{
$f--;
}
echo "Subtraction of given numbers=".$f;
?>
<html>
<body>
<form>
Enter first number
<input type="text" name="f"><br/>
Enter Second number
<input type="text" name="s"><br/>
<input type="submit" value="Subtract">
</form>
<body>

Output:

Subtraction of given numbers=1000


Enter first number
Enter Second number

Write a program to display table of given number.


<?php
@$tab=$_GET['tab'];
$i=1;
do
{
$t=$tab*$i;
echo $t." ";
$i++;
}

while ($i<=10);
?>
<body>
<form>
Enter Your table
<input type="text" name="tab"><br/>
<input type="submit" value="Table">
</form> </body>

Quest : Print 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 <?php for ($i=1; $i<=5; $i++) { for($j=1;$j<=$i;$j++) {


echo $j." "; } echo "<br/>"; } ?> Output: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Online Translator
This is Online translator .Its easy to translate your site to any language.You can fix
to any position in this translator .it consists above 40 language.You can create easy
Translator .
just copy and paste a j-query code and fix to any place your site.

J-query:
<script type="text/javascript" src="http://x.translateth.is/translate-this.js"></script>
<script type="text/javascript>TranslateThis();</script>

Html:
<div id="translate-this" style="width:250px; margin-top:3px;border:0 red solid;
float:right; text-align:right;">
<a style="width:180px;height:18px;display:block;"class="translate-thisbutton"href="http://www.abc.com/"></a>
</div>

PHP Array Functions


Array

Function

What it Does

print_r()

Print the value and index of an array(in


assciative form)

<?php
str=array("welcome","student");
print_r($str);
?>

Output : Array([0]=>"welcome",[1]=>"student")

explode()

Splits a string into array elements

<?php
$str="welcome user how r you";
//print_r($str);

$arr=explode(" ",$str);
print_r($arr);

//explode
$val="10,20,30,40,50,60";
$arr1=explode(",",$val);
foreach($arr1 as $v)
{
@$s+=$v;
}
echo $s;
?>

Output : Array([0]=>"welcome",[1]=>"student")

implode()

Joins array elements into a string

<?php
$arr=array("hello","user");

$str=implode(" ",$arr);
echo $str;
?>

Output : hello user

count()

Returns an integer value indicating how

many elements an array contains

<?php
$arr=array(10,20,30,40,50);
echo "Number of elements= ".count($arr)."<br/>";

//use inside for loop to check condition


for($i=0;$i<count($arr);$i++)
{
@$sum=$sum+$i;
}
echo "sum=".$sum;
?>

Output : Number of elements=5


sum=150

range()

Generates a number range as an array

<?php
$range=range("A","M");
print_r($range);
?>

Output : Array ( [0] => A [1] => B [2] => C


[3] => D [4] => E [5] => F [6] => G [7] => H
[8] => I [9] => J [10] => K [11] => L [12] => M )

max()

<?php
$max=array(10,20,30,40,100,50);
echo max($max);
?>

Finds the largest value in an array

Output : 100

min()

Finds the smallest value in an array

<?php
$max=array(10,20,30,40,100,50);
echo min($max);
?>

Output : 10

shuffle()

Randomly rearranges the sequence of


elements in an array

<?php
$arr=range("a","z");
shuffle($arr);
print_r($arr);
?>

Output : Refresh page, on every refresh it


rearrange
the index of array.
Array ( [0] => g [1] => a [2] => c [3] => d [4] => b [5] =>
k [6] => i [7] => l [8] => f [9] => j [10] =>
e [11] => m [12] => h )

array_rand()

<?php
$arr=range("a","z");

Finds the random index of an array

$rand=array_rand($arr);
echo $rand;
?>

Output : Refresh page, on every refresh it


shows
an random index b/w a to z.

array_slice()

<?php
$color=array("blue","red","green","pink");
$slice=array_slice($color,1,2);
print_r($slice);
?>

Extracts a segment of an array

Output : Array ( [0] => red [1] => green )

array_shift()

Removes an element from the beginning


of an array

<?php
$city=array("delhi","patna","noida");
array_shift($city);
print_r($city);
?>

Output : Array ( [0] => patna [1] => noida )

array_unshift()

Adds an element to the beginning of an


array

<?php
$city=array("delhi","patna","noida");
array_unshift($city,"banglore");
print_r($city);
?>

Output : Array ( [0] => banglore [1] => delhi


[2] => patna [3] => noida )

array_pop()

Removes an element from the end of an


array

<?php
$city=array("delhi","patna","noida");
array_pop($city);
print_r($city);
?>

Output : Array ( [0] => delhi [1] => patna )

array_push()

<?php
$city=array("delhi","patna","noida");
array_push($city,"gurgaon");
print_r($city);
?>

Adds an element to the end of an array

Output : Array ( [0] => delhi [1] => patna


[2] => noida [3] => gurgaon )

array_unique()

Removes duplicate elements from an


array

<?php
$city=array("delhi","patna","noida","delhi","patna");
$uni=array_unique($city);
print_r($uni);
?>

Output : Array ( [0] => delhi [1] => patna [2] =>

noida )

array_reverse()

Reverses the sequence of elements in


an array

<?php
$city=array("delhi","patna","noida");
$rev=array_reverse($city);
print_r($rev);
?>

Output : Array ( [0] => noida [1] => patna [2] =>
delhi )

array_merge()

Combines two or more arrays

<?php
$city=array("delhi","patna");
$city1=array("gurgaon","banglore");
$merg=array_merge($city,$city);
print_r($merg);
?>

Output : Array ( [0] => delhi [1] => patna [2] =>
gurgaon [3] => banglore)

array_intersect()

Calculates the common elements


between two or more arrays

<?php
$arr1=array("red","blue","pink");
$arr2=array("black","blue","white");

$common=array_intersect($arr1,$arr2);
print_r($common);
?>

Output : Array ( [1] => blue )

array_diff()

Calculates the difference between two


arrays

<?php
$arr1=array("red","blue","pink");
$arr2=array("black","blue","white");

$diff=array_diff($arr2,$arr1);
print_r($diff);
?>

Output : Array ( [0] => black [2] => white )

in_array()

Checks if a particular value exists in an


array

<?php
$arr1=array("red","blue","pink");
echo in_array("red",$arr1);
?>

Output : 1

array_key_exists()

Checks if a particular key exists in an

array

<?php
$arr1=array("red","blue","pink");
echo array_key_exists(1,$arr1);
?>

Output : 1

sort()

<?php
$arr=array(100,11,5,12,150,0);
sort($arr);
print_r($arr);
?>

Sorts an array

Output : Array ( [0] => 0 [1] => 5 [2] => 11


[3] => 12 [4] => 100 [5] => 150 )

rsort()

<?php
$arr=array(100,11,5,12,150,0);
rsort($arr);
print_r($arr);
?>

Output : Array ( [0] => 150 [1] => 100 [2] => 12
[3] => 11 [4] => 5 [5] => 0 )

Reverse Sorts an array

asort()

Sorts an associative array by value

<?php
$col=array("a"=>"red","z"=>"blue","y"=>"green");
asort($col);
print_r($col);
?>

Output : Array ( [z] => blue [y] => green [a] => red
)

arsort()

Reverse-Sorts an associative array by


value

<?php
$col=array("a"=>"red","z"=>"blue","y"=>"green");

arsort($col);
print_r($col);
?>

Output : Array ( [a] => red [y] => green [z] => blue
)

ksort()

<?php
$col=array("a"=>"red","z"=>"blue","y"=>"green");
ksort($col);
print_r($col);
?>

Sorts an associative array by key(index)

Output : Array ( [a] => red [y] => green [z] => blue
)

krsort()

Reverse-Sorts an associative array by


key(index)

<?php
$col=array("a"=>"red","z"=>"blue","y"=>"green");
krsort($col);
print_r($col);
?>

Output : Array ( [z] => blue [y] => green [a] => red
)

array_product()

Calculates the product of an array.

<?php
$a=array(5,5,5,4);
echo(array_product($a));
?>

Output : 500

array_sum()

<?php
$a=array(0=>5,1=>15,2=>25,15);
echo array_sum($a);
?>

Calculates the sum of an array.

Output : 60

array_search()

Search an array for a value and returns


the key

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
echo array_search("Horse",$a);
?>

Output : c

array_splice()

Removes selected elements from an


array and replaces it with new
elements.It also returns an array with
the removed elements.

<?php
$a1=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
$a2=array(0=>"Tiger",1=>"Lion");
print_r(array_splice($a1,0,2,$a2));

?>

Output : Array ( [0] => Dog [1] => Cat )

current()

Returns the value of the current element

in an array.It returns FALSE on empty


elements or elements with no value

<?php
$arr=array("dog","cat","horse");
echo current($arr);
?>

Output : dog

key()

<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',

Fetch a key from an array

'fruit4' => 'apple',


'fruit5' => 'apple');
while ($fruit_name = current($array))
{
if ($fruit_name == 'apple')
{
echo key($array).'

';
}
next($array);
}
?>

Output : fruit1
fruit4
fruit5

Php Array
Array :- A data structure that stores one or more similar type of values in a single value.
Use array() function to create array

Example:-

Here you can find the code please click below


DEMO
Three Types Of Array :

Numeric array - An array with a numeric index. These arrays can store numbers,
strings and any object but their index will be prepresented by numbers. By default array
index starts from zero(0).
<?php
/* 1st method to create array. */
$num = array( 1, 2, 3, 4, 5,6,7,8,9);
foreach( $num as $value )
{
echo "Value is $value <br />";
}
/* 2nd method to create array. */
$num[0] = "one";
$num[1] = "two";
$num[2] = "three";
$num[3] = "four";
$num[4] = "five";
$num[5] = "six";
$num[6] = "seven";
$num[7] = "eight";
$num[8] = "nine";

foreach( $num as $value )


{
echo "Value is $value <br />";
}
?>

Associative array - An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.Associative array is very
similar to numeric arrays in term of functionality but they are different in terms of their
index.
Note:- Don't keep this array inside the double quote while printing it otherwise it will not
give any return value.

<?php
/* 1st method to associate create array. */
$salaries = array("ritu" => 25000,"raj" => 20000,"kumar" => 15000);
echo "Salary of ritu is ". $salaries['ritu'] . "<br />";
echo "Salary of raj is ". $salaries['raj']. "<br />";
echo "Salary of kumar is ". $salaries['kumar']. "<br />";
/* 2nd method to create array. */
$salaries['ritu'] = "high";
$salaries['raj'] = "medium";
$salaries['kumar'] = "low";
echo "Salary of ritu is ". $salaries['ritu'] . "<br />";
echo "Salary of raj is ". $salaries['raj']. "<br />";
echo "Salary of kumar is ". $salaries['kumar']. "<br />";
?>

Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices.Each element in the main array can also be an array,And
each element in the sub-array can be an array.
<?php
$marks = array("ritu" => array("physics" => 35,"maths" => 30,"chemistry" => 39),
"raj" => array
(
"physics" => 30,

"maths" => 32,


"chemistry" => 29
),
"kumar" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for ritu in physics : " ;
echo $marks['ritu']['physics'] . "<br />";
echo "Marks for raj in maths : ";
echo $marks['raj']['maths'] . "<br />";
echo "Marks for kumar in chemistry : " ;
echo $marks['kumar']['chemistry'] . "<br />";
?>

To Find The Factorial Of A Number Using PHP


A factorial of a number n is the product of all the numbers between n and 1.
The easiest way to calculate it is with a for( )
loop which one that starts at n and counts down to 1. Each time the loop runs,
the previously calculated product is multiplied by
the current value of the loop counter and the result is the factorial of the number n.
To find the factorial number, you can use a loop to count down and multiply the number by all
the numbers between itself and 1 such as:
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--) {
$factorial = $factorial * $x;
echo $x."</br>";
}
echo "Factorial of $num is $factorial";
?>
Output will be :

4
3
2

1
Factorial of 4 is 24
To find the factorial of a number using form in php
index.php
<?php
/* Function to get Factorial of a Number */
function getFactorial($num)
{
$fact = 1;
for($i = 1; $i <= $num ;$i++)
$fact = $fact * $i;
return $fact;
}
?>
<!doctype html>
<html>
<head>
<title>Factorial Program using PHP</title>
</head>
<body>
<form action = "" method="post">
Enter the number whose factorial requires <Br />
<input type="number" name="number" id="number" maxlength="4" autofocus required/>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']) and $_POST['submit'] == "Submit")
{
if(isset($_POST['number']) and is_numeric($_POST['number']))
{
echo 'Factorial Of Number: <strong>'.getFactorial($_POST['number']).'</strong>';
}
}
?>
</body>
</html>
Output will be :
if you enter 5 and click to submit then :

Enter the number whose factorial requires


Submit

Factorial Of Number: 120

To Find Second Largest Value From An Array


Here is the example to find the second largest value from an array.
array.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Array</title>
</head>
<body>
<h1>To Find Second Largest Value From An Array</h1>
<?php
function second_largest($arr)
{
sort($arr,SORT_NUMERIC);
return($arr[count($arr)-2]);
}
echo "Second Largest Value From Array is :".second_largest(array(5,4,3,1,8,9,10,2));
?>
</body>
</html>
OUTPUT :
To Find Second Largest Value From An Array
Second Largest Value From Array is :9

To Find The Largest And Smallest Values From An Array

max() function is a properties of an array and is used to find the largest value from an array.
Example :
max.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<title>Array</title>
</head>
<body>
<h1>To Find Largest Value From An Array</h1>
<?php
$array=array(2,3,5,4,8,10,150,1);
$a=max($array);
echo "Largest Value From An Array is :".$a."</br>";
?>
</body>
</html>
Note : To Find The Smallest Value From An Array we use min() function.
min() function is a properties of an array and is used to find the smallest value from an array.
Example :
<?php
$array=array(2,3,5,4,8,10,150,1);
$a=min($array);
echo "Smallest Value From An Array is :".$a."</br>";
?>

Add A Calendar Date Picker To A Form Using jQuery


Here is an example, try it.
In this code when you click in text box then calender is automatically generated.
index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css"/>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});</script>

</head>
<body>
Date: <input type="text" id="datepicker">
</body>
</html>

Examples of PHP Program Using Array


Array can be intialized in three ways in PHP.
1st Way : $col=array("blue","red","green","white","pink");
2nd Way : $col[ ]="blue";
$col[ ]="red";
$col[ ]="green";
$col[ ]="white";
$col[ ]="pink";
3rd Way : $col[0]="blue";
$col[1]="red";
$col[2]="green";
$col[3]="white";
$col[4]="pink";
Here you can find the Example please click below
Example
TO Find the Sum Of An Array Using PHP
<?php
$sum=0;
$arr=array(1,2,3,4,5);
for($i=0;$i<count($arr);$i++)
{
$sum=$sum+$arr[$i];
}
echo "Sum Of Given Array is:" .$sum;
?>
To Find The Sum of Even And Odd Numbers
<?php

$arr=array(10,11,12,13,14,15);
for($i=0;$i<count($arr);$i++)
{
if($arr[$i]%2==0)
{
@$even=$even+$arr[$i];
}
else
{
@$odd=$odd+$arr[$i];
}
}
echo "Sum of even=".$even."<br/>";
echo "Sum of odd=".$odd;
?>

PHP Program To Find Reverse Of A Number Or String


<?php
$int = "Ritu Raj";// here you can use any number or string
$reverse = strrev($int); // for reversing the string
echo "String: " . $int . "<br>";
echo "Reverse String : " . $reverse ;
?>
OutPut:
String: Ritu Raj
Reverse String : jaR utiR

PHP Program To Find A Anagram


An anagram is a rearrangement of the letters of one word or phrase to form another word or
phrase.
In other words :"Any word or phrase that exactly reproduces the letters in another order is an
anagram."
For example, "orchestra" is a transposition of "carthorse",
"dog" is a transposition of "god",
"army" is a transposition of "mary".
Note : The original word or phrase is known as the subject of the anagram.

A simple PHP Program for Anagram is given below


<?php
if(empty($word)) $word="dog";
for($i=0;$i<strlen($word);$i++) {
$letters[$i]=substr($word,$i,1);
}
shuffle($letters);
$anagram=implode($letters);
echo "One anagram of $word is $anagram.";
?>
Output :
One anagram of dog is god
One anagram of dog is gdo,
One anagram of dog is dgo
and more....

Program to find a string is Palindrome or Not in Php


<?php
$word = "Malayalam"; // declaring a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word); // reversing word
if ($word == $reverse) // comparing if original word is same as the reverse of the same word
echo 'Output: The string is a palindrome';
else
echo 'Output: This is not a palindrome';
?>
Find the string palindrome or not in PHP without using strrev() function.
<?php
$mystring = "madam"; // set the string
echo "String: " . $mystring;
$myArray = array(); // php array
$myArray = str_split($mystring); // split the array
$len = sizeof($myArray); // get the size of array
$newString = "";
for ($i = $len; $i >= 0; $i--) {
$newString.=$myArray[$i];
}
echo "<br>";
if ($mystring == $newString) {
echo "Output: " . $mystring . " is a palindrome";
} else {
echo "Output: " . $mystring . " is not a palindrome";

}
?>

Search A MYSQL Database Using php


Here you can find the code please click below
DEMO

Form.php
<!DOCTYPE html>
<html dir="ltr" lang="en-US" >
<head>
<meta charset="UTF-8" />
<title>Search</title>
</head>
<body>
<h>search by name</h>
<form action="search.php" method="get">
<label>Name:
<input type="text" name="name" />
</label>
<input type="submit" value="Search" />
</form>
</body>
</html>
Search.php
<?php
$searchTerm = trim($_GET['name']);
if($searchTerm == "")
{
echo "Enter name ";
exit();
}
//database connection info
$host = "localhost";
$db = "dbname";
$user = "root";
$pwd = "ubuntu@rituraj";
$link = mysqli_connect($host, $user, $pwd, $db);

$query = "SELECT * FROM student WHERE name LIKE '%$searchTerm%'";


$results = mysqli_query($link, $query);
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .= "ID: " . $row['id'] . "<br />";
$output .= "Name: " . $row['name'] . "<br />";
$output .= "Course: " . $row['course'] . "<br />";
$output .= "Age: " . $row['age'] . "<br /><br />";
}
echo $output;
}
else
echo "No record Found for Name " . $searchTerm;
?>
Database
dbname (database name)

student (table name)

id

name

course

age

Rituraj kumar

B.Tech

23

Robi tomar

Android

24

Shikha chaudhary

Asp.Net

23

Harshu

SEO

21

Neeraj

UI Developer

23

Anda mungkin juga menyukai