How to run PHP code in XAMPP.docx (1).pdf

rajeswaria21 14 views 18 slides Jan 21, 2025
Slide 1
Slide 1 of 18
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18

About This Presentation

-


Slide Content

HowtorunPHPcodeinXAMPP
Generally,aPHPfilecontainsHTMLtagsandsomePHPscriptingcode.Itisveryeasyto
createasimplePHPexample.Todoso,createafileandwriteHTMLtags+PHPcodeand
savethisfilewith.phpextension.
Note:PHPstatementsendswithsemicolon(;).
AllPHPcodegoesbetweenthephptag.Itstartswith<?phpandendswith?>.Thesyntaxof
PHPtagisgivenbelow:
<?php   
//your code here  
?>  
Let'sseeasimplePHPexamplewherewearewritingsometextusingPHPechocommand.
<!DOCTYPE>  
<html>  
<body>  
<?php  
echo " <h2>Hello First PHP </h2>";  
?>  
</body>  
</html>  
HowtorunPHPprogramsinXAMPP
HowtorunPHPprogramsinXAMPPPHPisapopularbackendprogramminglanguage.
PHPprogramscanbewrittenonanyeditor,suchas-Notepad,Notepad++,Dreamweaver,
etc.Theseprogramssavewith .php extension,i.e.,filename.phpinsidethehtdocsfolder.
Forexample -p1.php.
AsI'musingwindow,andmyXAMPPserverisinstalledinDdrive.So,thepathforthe
htdocsdirectorywillbe"D:\xampp\htdocs".
PHPprogramrunsonawebbrowsersuchas-Chrome,InternetExplorer,Firefox,etc.Below
somestepsaregiventorunthePHPprograms.
Step1: CreateasimplePHPprogramlikehelloworld.
<?php      
    echo "Hello  World!";  
?>  
Step2: Savethefilewith hello.php nameinthehtdocsfolder,whichresidesinsidethe
xamppfolder.
Step3: RuntheXAMPPserverandstarttheApacheandMySQL.

Step4: Now,openthewebbrowserandtypelocalhost  http://localhost/hello.php onyour
browserwindow.
Step5: Theoutputfortheabove  hello.php programwillbeshownasthescreenshotbelow:
PHPCaseSensitivity
InPHP,keyword(e.g.,echo,if,else,while),functions,user-definedfunctions,classesarenot
case-sensitive.However,allvariablenamesarecase-sensitive.
Inthebelowexample,youcanseethatallthreeechostatementsareequalandvalid:
<!DOCTYPE>  
<html>  
    <body>  
        <?php  
            echo "Hello world using echo </br>";  
            ECHO "Hello world using ECHO </br>";  
            EcHo "Hello world using EcHo </br>";  
        ?>  
    </body>  
</html>  
Lookatthebelowexamplethatthevariablenamesarecasesensitive.Youcanseethe
examplebelowthatonlythesecondstatementwilldisplaythevalueofthe$color
variable.Becauseittreats$color,$ColoR,and$COLORasthreedifferentvariables:
<html>  
    <body>  
        <?php  
            $color = "black";  
            echo "My car is ". $ColoR ." </br>";  
            echo "My dog is ". $color ." </br>";  
            echo "My Phone is ". $COLOR ." </br>";  
        ?>  
    </body>  
</html>  

PHPEcho
PHPechoisalanguageconstruct,notafunction.Therefore,youdon'tneedtouseparenthesis
withit.Butifyouwanttousemorethanoneparameter,itisrequiredtouseparenthesis.
ThesyntaxofPHPechoisgivenbelow:
void echo (string $ar g1 [, string $... ] )  
PHPechostatementcanbeusedtoprintthestring,multi-linestrings,escapingcharacters,
variable,array,etc.Someimportantpointsthatyoumustknowabouttheechostatementare:
oechoisastatement,whichisusedtodisplaytheoutput.
oechocanbeusedwithorwithoutparentheses:echo(),andecho.
oechodoesnotreturnanyvalue.
oWecanpassmultiplestringsseparatedbyacomma(,)inecho.
oechoisfasterthantheprintstatement.
PHPecho:printingstring
<?php  
echo "Hello by PHP echo";  
?>  
PHPecho:printingmultilinestring
<?php  
echo "Hello by PHP echo  
this is multi line  
text printed by   
PHP echo statement  
";  
?>  
PHPecho:printingescapingcharacters
<?php  
echo "Hello escape \"sequence\" characters";  
?>  
PHPecho:printingvariablevalue
<?php  
$msg="Hello JavaTpoint PHP";  
echo "Message is: $msg";    
?>  

PHPVariable:Declaringstring,integer,andfloat
<?php  
$str="hello string";  
$x=200;  
$y=44.6;  
echo "string is: $str <br/>";  
echo "integer is: $x <br/>";  
echo "float is: $y <br/>";  
?>  
ODDorEVEN
<?php
$number=12;
if($number%2==0)
{
echo"$numberisEvenNumber";
}
else
{
echo"$numberisOddNumber";
}
?>
AddingTwoNumbers
<?php  
$x=15;  
$y=30;  
$z=$x+$y;  
echo "Sum: ",$z;  
?>  
SumofDigits
Tofindsumofdigitsofanumberjustaddallthedigits.
Forexample,
14597 = 1 + 4 + 5 + 9 + 7  

14597 = 26  
Logic:
oTakethenumber.
oDividethenumberby10.
oAddtheremaindertoavariable.
oRepeattheprocessuntilremainderis0.
Example:
<?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";  
 ?>  
TableofNumber
Atableofanumbercanbeprintedusingaloopinprogram.
Logic:
oDefinethenumber.
oRunforloop.
oMultiplythenumberwithforloopoutput.
Example:
<?php    
define('a', 7);   
for($i=1; $i<=10; $i++)   
{   
  echo $i*a;   
  echo '<br>';     
}  
?>  
FactorialProgram

Thefactorialofanumbernisdefinedbytheproductofallthedigitsfrom1ton
(including1andn).
Forexample,
4! = 4*3*2*1 = 24  
6! = 6*5*4*3*2*1 = 720  
Note:
oItisdenotedbyn!andiscalculatedonlyforpositiveintegers.
oFactorialof0isalways1.
Thesimplestwaytofindthefactorialofanumberisbyusingaloop.
TherearetwowaystofindfactorialinPHP:
oUsingloop
oUsingrecursivemethod
Logic:
oTakeanumber.
oTakethedescendingpositiveintegers.
oMultiplythem.
Example:
<?php  
$num = 4;  
$factorial = 1;  
for ($x=$num; $x>=1; $x--)   
{  
  $factorial = $factorial * $x;  
}  
echo "Factorial of $num is $factorial";  
?>  
FactorialusingRecursioninPHP
Factorialof6usingrecursionmethodisshown.
Example:
<?php  
function fact ($n)  
{  
    if($n <= 1)   
    {  
        return 1;  

    }  
    else   
    {  
        return $n * fact($n - 1);  
    }  
}  
echo "Factorial of 6 is " .fact(6);  
?>  
ArmstrongNumber
AnArmstrongnumberistheonewhosevalueisequaltothesumofthecubesofits
digits.
0,1,153,371,407,471,etcareArmstrongnumbers.
Forexample,
407 = (4*4*4) + (0*0*0) + (7*7*7)  
        = 64 + 0 + 343  
407 = 407  
Logic:
oTakethenumber.
oStoreitinavariable.
oTakeavariableforsum.
oDividethenumberwith10untilquotientis0.
oCubetheremainder.
oComparesumvariableandnumbervariable.
ArmstrongnumberinPHP
Belowprogramcheckswhether407isArmstrongornot.
Example:
<?php  
$num=407;  
$total=0;  
$x=$num;  
while($x!=0)  
{  
$rem=$x%10;  
$total=$total+$rem*$rem*$rem;  

$x=$x/10;  
}  
if($num==$total)  
{  
echo "Y es it is an  Armstrong number";  
}  
else  
{  
echo "No it is not an armstrong number";  
}  
?>  
FibonacciSeries
Fibonacciseriesistheoneinwhichyouwillgetyournexttermbyaddingprevious
twonumbers.
Forexample,
0 1 1 2 3 5 8 13 21 34  
Here, 0 + 1 = 1  
            1 + 1 = 2  
            3 + 2 = 5  
andsoon.
Logic:
oInitializingfirstandsecondnumberas0and1.
oPrintfirstandsecondnumber.
oFromnextnumber,startyourloop.Sothirdnumberwillbethesumofthefirsttwo
numbers.
Example:
<?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;  
?>  
FibonacciseriesusingRecursivefunction
Recursionisaphenomenoninwhichtherecursionfunctioncallsitselfuntilthebase
conditionisreached.
<?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";  
}  
Reversenumber
Anumbercanbewritteninreverseorder.
Forexample
12345=54321
Logic:

oDeclareavariabletostorereversenumberandinitializeitwith0.
oMultiplythereversenumberby10,addtheremainderwhichcomesafterdividingthe
numberby10.
ReversingNumberinPHP
Example:
Belowprogremshowsdigitsreversalof23456.
<?php  
$num = 23456;  
$revnum = 0;  
while ($num > 1)  
{  
$rem = $num % 10;  
$revnum = ($revnum * 10) + $rem;  
$num = ($num / 10);   
}  
echo "Reverse number of 23456 is: $revnum";  
?>  
ReverseString
Astringcanbereversedeitherusingstrrev()functionorsimplePHPcode.
Forexample,onreversingJAVATPOINTitwillbecomeTNIOPTAVAJ.
Logic:
oAssignthestringtoavariable.
oCalculatelengthofthestring.
oDeclarevariabletoholdreversestring.
oRunforloop.
oConcatenatestringinsideforloop.
oDisplayreversedstring.
ReverseStringusingstrrev()function
Areversestringprogramusingstrrev()functionisshown.
Example:
<?php  
$string = "JA VATPOINT";  
echo "Reverse string of $string is " .strrev ( $string );  

?>  
Swappingtwonumbers
Twonumberscanbeswappedorinterchanged.Itmeansfirstnumberwillbecome
secondandsecondnumberwillbecomefirst.
Forexample
a = 20, b = 30  
After swapping,  
a = 30, b = 20  
Therearetwomethodsforswapping:
oByusingthirdvariable.
oWithoutusingthirdvariable.
SwappingUsingThirdVariable
Swaptwonumbers45and78usingathirdvariable.
Example:
<?php  
$a = 45;  
$b = 78;  
// Swapping Logic  
$third = $a;  
$a = $b;  
$b = $third;  
echo "After swapping:<br><br>";  
echo "a =".$a."  b=".$b;  
?>  
SwappingWithoutusingThirdVariable
Swaptwonumberswithoutusingathirdvariableisdoneintwoways:
oUsingarithmeticoperation+and?
oUsingarithmeticoperation*and/
Examplefor(+and-):
<?php  
$a=234;  
$b=345;  
//using arithmetic operation  

$a=$a+$b;  
$b=$a-$b;  
$a=$a-$b;  
echo "V alue of a: $a</br>";  
echo "V alue of b: $b</br>";  
?>  
AreaofTriangle
AreaofatriangleiscalculatedbythefollowingMathematicalformula,
(base * height) / 2 =  Area  
AreaofTriangleinPHP
Programtocalculateareaoftrianglewithbaseas10andheightas15isshown.
Example:
<?php  
 $base = 10;  
 $height = 15;  
 echo "area with base $base and height $height= " . ($base * $height) / 2;  
 ?>  
AreaofaRectangle
Areaofarectangleiscalculatedbythemathematicalformula,
1.Length  ∗ Breadth =  Area  
Logic:
oTaketwovariables.
oMultiplybothofthem.
AreaofRectangleinPHP
Programtocalculateareaofrectanglewithlengthas14andwidthas12isshown.
Example:
Advertisement
<?php  
 $length = 14;  
 $width = 12;  
 echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";  
  ?>  
LeapYearProgram
Aleapyearistheonewhichhas366daysinayear.Aleapyearcomesafterevery
fouryears.Hencealeapyearisalwaysamultipleoffour.

Forexample,2016,2020,2024,etcareleapyears.
LeapYearProgram
Thisprogramstateswhetherayearisleapyearornotfromthespecifiedrangeof
years(1991-2016).
Example:
<?php  
function isLeap($year)  
{  
    return (date('L', mktime(0, 0, 0, 1, 1, $year))==1);  
}  
//For testing  
for($year=1991; $year<2016; $year++)  
{  
    If (isLeap($year))  
    {  
        echo "$year : LEAP YEAR<br />\n";  
    }  
    else  
    {  
        echo "$year : Not leap year<br />\n";  
    }  
}  
?>  
AlphabetTrianglePattern
Somedifferentalphabettrianglepatternsusingrange()functioninPHPareshown
below.
<?php  
$alpha = range('A', 'Z');  
for($i=0; $i<5; $i++){   
  for($j=5; $j>$i; $j--){  
    echo $alpha[$i];  
    }  
    echo "<br>";  
}  
?>  

StarTriangle
ThestartriangleinPHPismadeusingforandforeachloop.Therearealotofstar
patterns.We'llshowsomeofthemhere.
Pattern1
<?php  
for($i=0;$i<=5;$i++){  
for($j=5-$i;$j>=1;$j--){  
echo "* ";  
}  
echo "<br>";  
}  
?>  
Output:
Pattern2
<?php  
for($i=0;$i<=5;$i++){  
for($j=1;$j<=$i;$j++){  
echo "* ";  
}  
echo "<br>";  
}  
?>  
Output:

Pattern3
<?php  
for($i=0;$i<=5;$i++){  
for($k=5;$k>=$i;$k--){  
echo "  ";  
}  
for($j=1;$j<=$i;$j++){  
echo "*  ";  
}  
echo "<br>";  
}  
for($i=4;$i>=1;$i--){  
for($k=5;$k>=$i;$k--){  
echo "  ";  
}  
for($j=1;$j<=$i;$j++){  
echo "*  ";  
}  
echo "<br>";  
}  
?>  
Output:

Pattern4
<?php  
for($i=1; $i<=5; $i++){   
for($j=1; $j<=$i; $j++){   
echo ' * ';   
}  
echo '<br>';   
}  
for($i=5; $i>=1; $i--){   
for($j=1; $j<=$i; $j++){  
echo ' * ';   
}   
echo '<br>';   
}   
?>  
Output:

Pattern5
<?php  
for ($i=1; $i<=5; $i++)  
{  
 for ($j=1; $j<=5; $j++)  
  {  
   echo '* ';  
  }  
   echo "</br>";  
}  
?>  
Output:
Pattern6
<?php  
for($i=5; $i>=1; $i--)  
{  
if($i%2 != 0)  
{  
for($j=5; $j>=$i; $j--)  
{  
echo "* ";  
}  
echo "<br>";  
}  
}  
for($i=2; $i<=5; $i++)  
{  
 if($i%2 != 0)  
{  

 for($j=5; $j>=$i; $j--)  
{  
echo "* ";  
}  
echo "<br>";  
}  
}  
?>  
Tags