Actions

Difference between revisions of "PHP essentials"

From Joomla! Documentation

m (PHP Introduction)
m (updates)
 
(34 intermediate revisions by 6 users not shown)
Line 1: Line 1:
{{review}}
+
Many web designers and casual website owners are not conversant with the PHP language in which Joomla! is written and since Joomla! templates usually contain PHP statements it is necessary to understand at least a little of the language in order to be able to create or customize templates. This chunk will describe, in simple terms, how to use each aspect of PHP in the context of a Joomla! template. For example, a simple explanation of the PHP if-then-else syntax using extracts from a template for illustration.
Many web designers and casual website owners are not conversant with the
+
PHP language in which Joomla! is written and since Joomla! templates
+
usually contain PHP statements it is necessary to understand at least a
+
little of the language in order to be able to create or customize
+
templates. This chunk will describe, in simple terms, how to use each aspect of PHP in the
+
context of a Joomla! template. For example, a simple explanation of the PHP
+
if-then-else syntax using extracts from a template for illustration.
+
  
 
The best resource to learn PHP is probably hands on experience and Joomla can provide that to you thanks to it's native PHP code.  This can be overwhelming for people who have not programmed before. Though Joomla is easy enough to [[Installation|install]] with the help of the community and a little of your time you'll have people asking you to do their websites.
 
The best resource to learn PHP is probably hands on experience and Joomla can provide that to you thanks to it's native PHP code.  This can be overwhelming for people who have not programmed before. Though Joomla is easy enough to [[Installation|install]] with the help of the community and a little of your time you'll have people asking you to do their websites.
Line 12: Line 5:
 
One place that has a nice short list if functions and examples is http://en.wikiversity.org/wiki/25_Essential_PHP_Functions which is good to get familiar with PHP. Though for an extensive function list, explanations, and examples go to http://www.php.net.
 
One place that has a nice short list if functions and examples is http://en.wikiversity.org/wiki/25_Essential_PHP_Functions which is good to get familiar with PHP. Though for an extensive function list, explanations, and examples go to http://www.php.net.
  
Once you have the basics of PHP you'll need to get the basics of the Joomla PHP syntax.  Start by looking at some existing {{jsite|ext|extensions}} and check out the code and also take a look at some these Tutorials about Joomla:
+
Once you have the basics of PHP you'll need to get the basics of the Joomla PHP syntax.  Start by looking at some existing [http://extensions.joomla.org extensions] and check out the code and also take a look at some these Tutorials about Joomla:
  
[http://developer.joomla.org/tutorials/184-how-to-create-a-joomla-plugin.html How to create a Joomla! Plugin]
+
* [[Developing a MVC Component]]
 
+
* [[Creating a Plugin for Joomla]]
[http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_1 Developing a Model-View-Controller Component - Part 1]
+
* [[Creating a simple module]]
 
+
[http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_2_-_Adding_a_Model Developing a Model-View-Controller Component - Part 2 - Adding a Model]
+
 
+
[http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_3_-_Using_the_Database Developing a Model-View-Controller Component - Part 3 - Using the Database]
+
 
+
[http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_4_-_Creating_an_Administrator_Interface Developing a Model-View-Controller Component - Part 4 - Creating an Administrator Interface]
+
  
 
That will help you get familiar with some of the functions available within Joomla's system and what they do (using the API).  Take particular care to understand the MVC (model view control) setup.
 
That will help you get familiar with some of the functions available within Joomla's system and what they do (using the API).  Take particular care to understand the MVC (model view control) setup.
Line 29: Line 16:
  
 
==== PHP Introduction ====
 
==== PHP Introduction ====
PHP is a scripting language designed primarily for producing dynamic web pages. It is embedded into an HTML page with tags like <?php ... ?>. When a page is passed on to the PHP engine, the PHP tags are translated into HTML, which can then be rendered by a browser. A database is needed during translation since the script may need to pull data from the database. So to create PHP pages, we require the PHP engine, a database (typically MySQL) and the webserver, which will coordinate these actions and forward the final HTML to the browser. These three components can be installed separately; however, we have packages like WAMP (for Windows), MAMP (for Mac) and LAMP (for Linux), for your convenience. Installation of the packages is discussed next.
+
PHP is a scripting language designed primarily for producing dynamic web pages. It is embedded into an HTML page with tags like <?php...?>. When a page is sent to the PHP engine, the PHP tags are translated into HTML, which can then be rendered by a browser. A database is needed during translation since the script may need to pull data from the database. So to create PHP pages, we require the PHP engine, a database (typically MySQL) and the webserver, which will coordinate these actions and forward the final HTML to the browser. These three components can be installed separately; however, we have packages like WAMP (for Windows), MAMP (for Mac) and LAMP (for Linux), for your convenience.
  
 
==== PHP Installation ====
 
==== PHP Installation ====
 
The packages can be downloaded from [http://www.wampserver.com/en/download.php WAMP]. WAMP stands for Windows Apache MySQL PHP. The instructions can be followed as given in the site and is pretty straightforward. The installation can be done is any directory (say D:/wamp). Once installed, it can be started from the program->start->WampServer. This should give a small icon in the system tray using which the server can be started/stopped/restarted. It also gives links to all important files like php.ini and other configuration files. For Mac users MAMP can be found [http://www.macupdate.com/info.php/id/16197 here]. For the purpose of this tutorial [http://www.apachefriends.org/en/xampp.html XAMPP] can also be used.
 
The packages can be downloaded from [http://www.wampserver.com/en/download.php WAMP]. WAMP stands for Windows Apache MySQL PHP. The instructions can be followed as given in the site and is pretty straightforward. The installation can be done is any directory (say D:/wamp). Once installed, it can be started from the program->start->WampServer. This should give a small icon in the system tray using which the server can be started/stopped/restarted. It also gives links to all important files like php.ini and other configuration files. For Mac users MAMP can be found [http://www.macupdate.com/info.php/id/16197 here]. For the purpose of this tutorial [http://www.apachefriends.org/en/xampp.html XAMPP] can also be used.
  
==== PHP Round trip ====
+
==== PHP Round-trip ====
Our primary target here is to write a small PHP page and get it rendered by the Apache web server. To render a page WAMP by default looks into the www folder of the WAMP install directory referred henceforth as WAMP_HOME for convenience. Fire up your primary text editor and create a page say first.php and save it in the WAMP_HOME/www/x/y folder, where x, y are folders (which you can create for organizing your scripts). Write the following in the script
+
Our primary objective here is to write a small PHP page and have it rendered by the Apache web server. WAMP renders a page by looking in the www folder of the WAMP Install Directory, hereafter referred to as WAMP_HOME. Fire up your primary text editor, create a page and name it, say, first.php, and save it to the WAMP_HOME/www/x/y folder (x and y are folders created to organize the scripts) and write the following in the script:
  
 
<source lang="php">
 
<source lang="php">
Line 44: Line 31:
 
<body>
 
<body>
 
<?php
 
<?php
echo ("My first php snippet");
+
echo "My first php snippet";
 
?>
 
?>
 
</body>
 
</body>
Line 50: Line 37:
 
</source>
 
</source>
  
Save this file and point your browser to http://localhost/x/y/first.php and you should be able to see the echo message.  
+
Save this file, point your browser to '''<nowiki>http://localhost/x/y/first.php</nowiki>''', and you should be able to see the echo message.  
  
Primary things to note here are <pre>
+
The primary things to note here are: <pre>
1. It is strongly advised to start any PHP code by "<?php" and end with a "?>" tag.  
+
1. It is strongly advised that all PHP codes begin with: "<?php" and end with a "?>" tag.  
2. To have a semicolon after each PHP statement.
+
2. To have a semicolon [;] after each PHP statement.
3. The directory in which this script resides needs to be given in the URL.  
+
3. The directory where this script resides needs to be given in the URL.  
 
</pre>
 
</pre>
  
This completes our round trip. Now for the sake of learning either you can keep including new elements in this file or may create separate scripts and load them in the browser.
+
This completes our round-trip. Now, for the sake of learning, you can either keep including new elements in this file or you can create separate scripts and load them in the browser.
  
==== PHP Variable declaration and Data types ====
+
==== PHP Variable Declaration and Data Types ====
For any programming we need to hold data. In PHP following are the ways in which you can define variables.
+
We need to hold data for any programming. Following are ways you can define variables in PHP:
 
<ol>
 
<ol>
 
<li>$variable_name = 0; </li>
 
<li>$variable_name = 0; </li>
Note here we did not define what is the type of variable, whether integer or string that the variable should hold. This is referred to as dynamic scoping.  
+
'''Note''': here we did not define the type of variable, whether integer or string, that the variable should hold. This is referred to as dynamic scoping.  
 
<li> the variable names should start with an alphabet and can contain alphanumeric characters and "_"
 
<li> the variable names should start with an alphabet and can contain alphanumeric characters and "_"
 
<li> Defining constants - <source lang="php"> define ("NAME_OF_THE_CONSTANT" , $value); </source> </li>
 
<li> Defining constants - <source lang="php"> define ("NAME_OF_THE_CONSTANT" , $value); </source> </li>
 
</ol>
 
</ol>
  
==== Basic operators ====
+
==== Basic Operators ====
The general operators are as below and explained.
+
The general operators are explained below:
 
<pre>
 
<pre>
 
a. +  e.g. 6 + 3, addition operator, answer is 9
 
a. +  e.g. 6 + 3, addition operator, answer is 9
Line 97: Line 84:
 
</pre>
 
</pre>
  
==== Defining array Structures ====
+
==== Defining Array Structures ====
 
'''Ways of declaring arrays'''  
 
'''Ways of declaring arrays'''  
<br> Suppose we want many variables, we could have done in the way declaring variables as above, however, that is not elegant, for suppose u want a 100 variables; declaring arrays come to the rescue. Note that index in PHP starts from 0.
+
<br> Suppose we want many variables. We could have declared the variables as shown above; however, that is not elegant. Suppose you want 100 variables; declaring arrays come to the rescue. Note that the index in PHP starts with 0.
<pre>
+
<source lang="php">
$my_guitar_heroes = array ("Hendrix", "Schenker", "Gilmour", "to_name_a_few!");
+
$my_guitar_heroes = array ("Hendrix", "Shankar", "Gilmour", "to_name_a_few!");
</pre>
+
</source>
 
Or
 
Or
<pre>
+
<source lang="php">
 
$my_guitar_heroes [] = "Hendrix";
 
$my_guitar_heroes [] = "Hendrix";
$my_guitar_heroes [] = "Schenker";
+
$my_guitar_heroes [] = "Shankar";
 
$my_guitar_heroes [] = "Gilmour";
 
$my_guitar_heroes [] = "Gilmour";
 
$my_guitar_heroes [] = "to_name_a_few!";
 
$my_guitar_heroes [] = "to_name_a_few!";
</pre>
+
</source>
 
Here PHP automatically assigns the index.
 
Here PHP automatically assigns the index.
  
 
Or
 
Or
<pre>
+
<source lang="php">
 
$my_guitar_heroes [0] = "Hendrix";
 
$my_guitar_heroes [0] = "Hendrix";
 
$my_guitar_heroes [10000] = "Mainak";
 
$my_guitar_heroes [10000] = "Mainak";
</pre>
+
</source>
Here in I just knew the first element and the 10,001st element and that's me!
+
Here, I knew the first and the 10,001st element but that's me!
  
 
Or
 
Or
Line 123: Line 110:
  
 
Or
 
Or
<pre>
+
<source lang="php">
 
// Set the elements at positions 1 through 9999 to the value, "to be decided".
 
// Set the elements at positions 1 through 9999 to the value, "to be decided".
 
$my_guitar_heroes  = array_fill( 1, 9999, "to be decided" );  
 
$my_guitar_heroes  = array_fill( 1, 9999, "to be decided" );  
</pre>
+
</source>
  
'''Accessing the arrays'''  
+
'''Accessing the Arrays'''  
<pre>
+
<source lang="php">
print $my_guitar_heroes[2]; //Access the 2nd element
+
print $my_guitar_heroes[2]; //Access the 3rd element
</pre>
+
</source>
 
Or
 
Or
<pre>
+
<source lang="php">
 
// Access the last element (Note that the element positions are numbered zero to  
 
// Access the last element (Note that the element positions are numbered zero to  
 
// [number of elements] minus one.)
 
// [number of elements] minus one.)
 
$my_guitar_heroes[count($my_guitar_heroes)-1];  
 
$my_guitar_heroes[count($my_guitar_heroes)-1];  
</pre>
+
</source>
 
Or
 
Or
<pre>
+
<source lang="php">
 
// Access the last element using a function call.
 
// Access the last element using a function call.
 
end($my_guitar_heroes);  
 
end($my_guitar_heroes);  
</pre>
+
</source>
  
'''Iterating over the element of an array'''  
+
'''Iterating Over the Element of an Array'''  
<pre>
+
<source lang="php">
 
foreach ( $my_guitar_heroes as $temp) {
 
foreach ( $my_guitar_heroes as $temp) {
 
   print "$temp<br />";
 
   print "$temp<br />";
 
}
 
}
</pre>
+
</source>
 
+
==== Control expressions ====
+
To execute a statement of collection of statements over and over, we use Control expressions. The  following are general syntax of the control structures
+
  
 +
==== Control Expressions ====
 +
To execute a statement of a collection of statements over and over, we use Control Expressions. The general syntax of the control structures are as follows:
  
 
'''if statements'''<br>  
 
'''if statements'''<br>  
Line 178: Line 164:
 
while ( $x <= 10 ) {
 
while ( $x <= 10 ) {
 
  print "$x<BR/>";
 
  print "$x<BR/>";
 +
$x++;
 
}
 
}
 
</source>
 
</source>
Line 190: Line 177:
 
</source>
 
</source>
  
==== Defining functions ====
+
==== Defining Functions ====
Code which is duplicated at many places are best placed in a function. Following are the ways of describing the function.
+
Code which is duplicated in many places is best placed in a function. The following are the ways of describing the function:
 
<source lang="php">
 
<source lang="php">
 
function name_of_the_function( $arguments, $size='default_values_if_any' ) {
 
function name_of_the_function( $arguments, $size='default_values_if_any' ) {
Line 198: Line 185:
 
}
 
}
 
</source>
 
</source>
The arguments are passed by value. If they are to be passed by reference then an argument is prefixed by "&" as below
+
The arguments are passed by value. If they are to be passed by reference, then an argument is prefixed by "&" as below:
 
<source lang="php">
 
<source lang="php">
 
function name_of_the_function( &$arguments, $size='default_values_if_any' ) {
 
function name_of_the_function( &$arguments, $size='default_values_if_any' ) {
Line 205: Line 192:
 
}
 
}
 
</source>
 
</source>
Scope of a variables defined within a function is valid within the function only.  
+
The scope of a variable defined within a function is valid only within that function.  
  
 
Calling a function
 
Calling a function
Line 212: Line 199:
 
==== Debugging ====
 
==== Debugging ====
 
'''Basic printing options''' <br/>
 
'''Basic printing options''' <br/>
A basic way to debug is to print the value of the variable. The following basic statments acheives that
+
A basic way to debug is to print the value of the variable. The following basic statements achieve that:
  
<ul>
+
* <code>echo "if double quotes are used then dollar variables are resolved";</code>
<li>echo "if double quotes are used then dollar variables are resolved";
+
* <code>echo 'if single quote are used then dollar variables are not resolved';</code>
<li>echo 'if single quote are used then dollar variables are not resolved';
+
* <code>print "another way to print";</code>
<li>print "another way to print";
+
* <code>nl2br("any new line characters like \n get automatically resolved to HTML line breaks");</code>
<li>nl2br("any new line characters like \n get automatically resolved to HTML line breaks");
+
</ul>
+
  
Apart from these the log files are very helpful and can be found in the WAMP_HOME/logs directory.
+
Apart from these, the log files are very helpful and can be found in the WAMP_HOME/logs directory.
  
==== Handling forms ====
+
==== Handling Forms ====
PHP does not change any HTML structure, thus any syntax of HTML remains the same. The part that PHP plays is making any part dynamic for e.g the action attribute of a form can be coded as action=<?php my_own_action(); ?> so that it is dynamically generated. The part where PHP kicks in is after the form is submitted, to say obtain the values of the form fields, set cookies etc. For this super global variables are used which are always available to PHP code. Some of these are   
+
{{warning|Joomla! provides [[Retrieving and Filtering GET and POST requests with JRequest::getVar|a safer and cleaner method of accessing request data]] and alternative ways for accessing the session. Using any of these arrays is not recommended.}}
<ol>
+
 
<li>$_GET - get the data from a GET request</li>
+
PHP does not change any HTML structure, thus any syntax of HTML remains the same. The part that PHP plays is making any part dynamic for e.g., the action attribute of a form can be coded as action=<?php my_own_action(); ?> so that it is dynamically generated. The part where PHP kicks in is after the form is submitted, say to obtain the values of the form fields, set cookies, etc. For this, super global variables are used, which are always available to PHP code. Some of these are:  
<li>$_POST - get the data from a POST request</li>
+
<li>$_REQUEST - get the request</li>
+
<li>$_COOKIE - obtain the cookies from the browser</li>
+
<li>$_SESSION - obtain the session</li>
+
</ol>
+
  
All of these are arrays and behave accordingly.
+
# <code>$_GET</code> - get the data from a GET request
 +
# <code>$_POST</code> - get the data from a POST request
 +
# <code>$_REQUEST</code> - get the request
 +
# <code>$_COOKIE</code> - obtain the cookies from the browser
 +
# <code>$_SESSION</code> - obtain the session
  
----
+
These are all arrays, and behave accordingly.
[[Category:Templates]]
+
<noinclude>[[Category:Development]][[Category:Tutorials]]</noinclude>

Latest revision as of 09:01, 22 June 2013

Many web designers and casual website owners are not conversant with the PHP language in which Joomla! is written and since Joomla! templates usually contain PHP statements it is necessary to understand at least a little of the language in order to be able to create or customize templates. This chunk will describe, in simple terms, how to use each aspect of PHP in the context of a Joomla! template. For example, a simple explanation of the PHP if-then-else syntax using extracts from a template for illustration.

The best resource to learn PHP is probably hands on experience and Joomla can provide that to you thanks to it's native PHP code. This can be overwhelming for people who have not programmed before. Though Joomla is easy enough to install with the help of the community and a little of your time you'll have people asking you to do their websites.

One place that has a nice short list if functions and examples is http://en.wikiversity.org/wiki/25_Essential_PHP_Functions which is good to get familiar with PHP. Though for an extensive function list, explanations, and examples go to http://www.php.net.

Once you have the basics of PHP you'll need to get the basics of the Joomla PHP syntax. Start by looking at some existing extensions and check out the code and also take a look at some these Tutorials about Joomla:

That will help you get familiar with some of the functions available within Joomla's system and what they do (using the API). Take particular care to understand the MVC (model view control) setup.

If however, you are absolutely new to PHP, following may help as very brief introduction to PHP.

Contents

PHP Introduction

PHP is a scripting language designed primarily for producing dynamic web pages. It is embedded into an HTML page with tags like <?php...?>. When a page is sent to the PHP engine, the PHP tags are translated into HTML, which can then be rendered by a browser. A database is needed during translation since the script may need to pull data from the database. So to create PHP pages, we require the PHP engine, a database (typically MySQL) and the webserver, which will coordinate these actions and forward the final HTML to the browser. These three components can be installed separately; however, we have packages like WAMP (for Windows), MAMP (for Mac) and LAMP (for Linux), for your convenience.

PHP Installation

The packages can be downloaded from WAMP. WAMP stands for Windows Apache MySQL PHP. The instructions can be followed as given in the site and is pretty straightforward. The installation can be done is any directory (say D:/wamp). Once installed, it can be started from the program->start->WampServer. This should give a small icon in the system tray using which the server can be started/stopped/restarted. It also gives links to all important files like php.ini and other configuration files. For Mac users MAMP can be found here. For the purpose of this tutorial XAMPP can also be used.

PHP Round-trip

Our primary objective here is to write a small PHP page and have it rendered by the Apache web server. WAMP renders a page by looking in the www folder of the WAMP Install Directory, hereafter referred to as WAMP_HOME. Fire up your primary text editor, create a page and name it, say, first.php, and save it to the WAMP_HOME/www/x/y folder (x and y are folders created to organize the scripts) and write the following in the script:

<html>
<head>
   <title>Basic PHP Page</title>
</head>
<body>
<?php
echo "My first php snippet";
?>
</body>
</html>

Save this file, point your browser to http://localhost/x/y/first.php, and you should be able to see the echo message.

The primary things to note here are:
1. It is strongly advised that all PHP codes begin with: "<?php" and end with a "?>" tag. 
2. To have a semicolon [;] after each PHP statement.
3. The directory where this script resides needs to be given in the URL. 

This completes our round-trip. Now, for the sake of learning, you can either keep including new elements in this file or you can create separate scripts and load them in the browser.

PHP Variable Declaration and Data Types

We need to hold data for any programming. Following are ways you can define variables in PHP:

  1. $variable_name = 0;
  2. Note: here we did not define the type of variable, whether integer or string, that the variable should hold. This is referred to as dynamic scoping.

  3. the variable names should start with an alphabet and can contain alphanumeric characters and "_"
  4. Defining constants -
     define ("NAME_OF_THE_CONSTANT" , $value);

Basic Operators

The general operators are explained below:

a.	+   e.g. 6 + 3, addition operator, answer is 9
b.	–   e.g. 6 - 3, subtraction operator, answer is 3
c.	/   e.g. 6 / 3, division operator, answer is 2
d.	*   e.g. 6 * 3, multiplication operator, answer is 18
e.	%   e.g. 6 % 3, modulus operator, answer is 0
f.	.   e.g. '6'.'3', concatenation operator, gives string '63'
g.	+=   e.g. $x += 6, adds 6
h.	-=   e.g. $x -= 6, subtracts 6
i.	/=   e.g. $x /= 6, divides by 6
j.	%=   e.g. $x %= 6, modulus by 6
k.	.=   e.g. $x .= '6', concats 6 to x
l.	<   e.g. $x < $y, evaluates to true if $x is < $y
m.	>   e.g. $x > $y, evaluates to true if $x is > $y
n.	==  e.g. $x == $y, evaluates to true if $x is equal by value to $y
o.	!=  e.g. $x != $y, evaluates to true if $x is not equal to $y
p.	===   e.g. $x === $y, evaluates to true if $x is and $y is identical i.e both of same type both value and reference
q.	>=  e.g. $x >= $y, evaluates to true if $x is >= $y
r.	<=  e.g. $x <= $y, evaluates to true if $x is <= $y
s.	&&  e.g. ($x == 2 && $y == 3) , evaluates to true if $x equals 2 and $y equals 3
t.	||  e.g. ($x == 2 || $y == 3) , evaluates to true if either $x equals 2 or $y equals 3
u.	xor e.g. ($x == 2 xor $y == 3) , evaluates to true if either $x equals 2 or $y equals 3 but not both
v.	++  e.g. $x++, increments $x
w.	–-  e.g. $x--, decrements $x

Defining Array Structures

Ways of declaring arrays
Suppose we want many variables. We could have declared the variables as shown above; however, that is not elegant. Suppose you want 100 variables; declaring arrays come to the rescue. Note that the index in PHP starts with 0.

$my_guitar_heroes = array ("Hendrix", "Shankar", "Gilmour", "to_name_a_few!");

Or

$my_guitar_heroes [] = "Hendrix";
$my_guitar_heroes [] = "Shankar";
$my_guitar_heroes [] = "Gilmour";
$my_guitar_heroes [] = "to_name_a_few!";

Here PHP automatically assigns the index.

Or

$my_guitar_heroes [0] = "Hendrix";
$my_guitar_heroes [10000] = "Mainak";

Here, I knew the first and the 10,001st element but that's me!

Or a combination of the above means

Or

// Set the elements at positions 1 through 9999 to the value, "to be decided".
$my_guitar_heroes  = array_fill( 1, 9999, "to be decided" );

Accessing the Arrays

print $my_guitar_heroes[2]; //Access the 3rd element

Or

// Access the last element (Note that the element positions are numbered zero to 
// [number of elements] minus one.)
$my_guitar_heroes[count($my_guitar_heroes)-1];

Or

// Access the last element using a function call.
end($my_guitar_heroes);

Iterating Over the Element of an Array

foreach ( $my_guitar_heroes as $temp) {
  print "$temp<br />";
}

Control Expressions

To execute a statement of a collection of statements over and over, we use Control Expressions. The general syntax of the control structures are as follows:

if statements

if( $x > 0) {   
 print("$x is positive");
}  else if( $x < 0 ) {  
 print("$x is negative");
} else {
 print("$x is 0");
}

for loop

for ( $x=1; $x<= 10; $x++ ) {
 print "$x<BR/>";
}

while loop

$x = 1
while ( $x <= 10 ) {
 print "$x<BR/>";
 $x++;
}

do while loop

$x = 1;
do {
 print "$x<BR/>";
 $x++;
}while($x <= 10);

Defining Functions

Code which is duplicated in many places is best placed in a function. The following are the ways of describing the function:

function name_of_the_function( $arguments, $size='default_values_if_any' ) {
  print "here goes in the code"; 
  return "this value is returned, return statement is optional";
}

The arguments are passed by value. If they are to be passed by reference, then an argument is prefixed by "&" as below:

function name_of_the_function( &$arguments, $size='default_values_if_any' ) {
  print "here goes in the code"; 
  return "this value is returned, return statement is optional";
}

The scope of a variable defined within a function is valid only within that function.

Calling a function

$x = add(5, 3);

Debugging

Basic printing options
A basic way to debug is to print the value of the variable. The following basic statements achieve that:

  • echo "if double quotes are used then dollar variables are resolved";
  • echo 'if single quote are used then dollar variables are not resolved';
  • print "another way to print";
  • nl2br("any new line characters like \n get automatically resolved to HTML line breaks");

Apart from these, the log files are very helpful and can be found in the WAMP_HOME/logs directory.

Handling Forms

Stop hand nuvola.svg.png
Warning!

Joomla! provides a safer and cleaner method of accessing request data and alternative ways for accessing the session. Using any of these arrays is not recommended.


PHP does not change any HTML structure, thus any syntax of HTML remains the same. The part that PHP plays is making any part dynamic for e.g., the action attribute of a form can be coded as action=<?php my_own_action(); ?> so that it is dynamically generated. The part where PHP kicks in is after the form is submitted, say to obtain the values of the form fields, set cookies, etc. For this, super global variables are used, which are always available to PHP code. Some of these are:

  1. $_GET - get the data from a GET request
  2. $_POST - get the data from a POST request
  3. $_REQUEST - get the request
  4. $_COOKIE - obtain the cookies from the browser
  5. $_SESSION - obtain the session

These are all arrays, and behave accordingly.